python socket的c/s模式

来源:互联网 发布:信捷xc3软件 编辑:程序博客网 时间:2024/04/29 08:43

1、TCP建立连接的方法:
服务端:
第一步:建立socket对象;
第二步:设置socket选项(可选)
第三步:绑定到一个端口,也可以是一个网卡;
第四步:倾听连接。

客户端:
第一步:建立socket对象;
第二步:调用connect()建立一个和服务器的连接

2、服务端:

#!/usr/local/Python34/bin/python3#coding=gbkimport socket, tracebackhost = ''port = 51423#建立socket对象s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#设置和得到socket对象;当socket关闭后,本地端用于该socket的端口号立刻就可以被重用。s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#绑定到一个端口s.bind((host, port))#倾听连接s.listen(1)print("done")while 1:    #when connect error happen, skip the error    try:        ClientSock, ClientAddr = s.accept()    except KeyboardInterrupt:        raise    except:        traceback.print_exc()        continue    #Get informaion form client and reply    try:        print("Get connect from ", ClientSock.getpeername())        data = ClientSock.recv(1024)        print("The information we get is %s" % str(data))        ClientSock.sendall(("I`ve got the information: ").encode())        ClientSock.sendall((data.decode()).encode())        while 1:            str = input("What you want to say:")            ClientSock.sendall(str.encode())            ClientSock.sendall(('\n').encode())    except (KeyboardInterrupt ,SystemError):        raise    except:        traceback.print_exc()    #Clocs socket    try:        ClientSock.close()    except KeyboardInterrupt:        raise    except:        traceback.print_exc()

3、客户端

#!/usr/local/Python34/bin/python3#coding=gbkimport socket, syshost = '10.15.89.150'# host = raw_input("Plz imput destination IP:")  # data = raw_input("Plz imput what you want to submit:")port = 51423'''socket 模块中的socket(family,type[,proto])函数创建一个新的socket对象。family的取值通常是AF_INET。type 的取值通常是SOCK_STREAM(用于定向的连接,可靠的TCP连接)或SOCK_DGRAM(用于UDP):'''s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  try:    s.connect((host, port))  except socket.gaierror as e:    print("Address-related error connecting to server: %s" %e)    sys.exit(1)  except socket.error as e:    print("Connection error: %s" %e)    sys.exit(1)data = input("Plz imput what you want to submit:")s.send(data.encode())s.shutdown(1)print("Submit Complete")while 1:          buf = s.recv(1024).decode()        sys.stdout.write(buf)
0 0
原创粉丝点击