服务器端:
1.创建一个面向网络的TCP套接字对象socket,
2.绑定地址和端口
3.监听
4.当有客户端连接时候,接受连接并给此连接分配一个新的套接字
5.当客户端发送空信息时候,关闭新分配的套接字
1 import socket 2 from time import ctime 3 4 HOST = '' 5 PORT = 50029 6 BUFSIZE = 1024 7 ADDR = (HOST,PORT) 8 tcpserver = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 9 tcpserver.bind(ADDR) 10 tcpserver.listen(5) 11 12 while True: 13 print('waiting for connecting...') 14 tcpconn,addr = tcpserver.accept() 15 print('...connected from:',addr) 16 17 while True: 18 data = tcpconn.recv(BUFSIZE).decode() 19 if not data: 20 break 21 tcpconn.send(('[{0}]{1}'.format(ctime(),data)).encode()) 22 23 tcpconn.close()
客户端:
1.创建新的套接字
2.连接指定的地址和端口号
1 import socket 2 3 HOST = 'localhost' 4 PORT = 50029 5 BUFSIZE = 1024 6 ADDR = (HOST,PORT) 7 8 tcpconn = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 9 tcpconn.connect(ADDR) 10 11 while True: 12 data = input('>') 13 if not data: 14 break 15 tcpconn.send(data.encode()) 16 data = tcpconn.recv(BUFSIZE).decode() 17 if not data: 18 break 19 print(data) 20 21 tcpconn.close()