1.tcp服务端server
1 from socket import * 2 from time import ctime 3 4 HOST = '' 5 PORT = 9999 6 BUFSIZ = 1024 7 ADDR = (HOST, PORT) 8 9 tcpSerSock = socket(AF_INET, SOCK_STREAM) #创建套接字 10 tcpSerSock.bind(ADDR) #绑定IP和端口 11 tcpSerSock.listen(5) #监听端口,最多5人排队 12 13 while True: 14 print('waiting for connection...') 15 tcpCliSock, addr = tcpSerSock.accept() #建立连接 16 print('...connected from:', addr) 17 18 while True: 19 data = tcpCliSock.recv(BUFSIZ) 20 if not data: 21 break 22 content = '[%s] %s' % (bytes(ctime(), "utf-8"), data) 23 print(data) 24 print(type(content)) 25 tcpCliSock.send(content.encode("utf-8")) 26 27 tcpCliSock.close() 28 29 tcpSerSock.close()
2.tcp客户端client
1 from socket import * 2 3 HOST = '127.0.0.1' # or 'localhost' 4 PORT = 9999 5 BUFSIZ = 1024 6 ADDR = (HOST, PORT) 7 8 tcpCliSock = socket(AF_INET, SOCK_STREAM) 9 tcpCliSock.connect(ADDR) 10 11 while True: 12 data = input('> ') 13 if not data: 14 break 15 16 tcpCliSock.send(data.encode("utf-8")) 17 data = tcpCliSock.recv(BUFSIZ) 18 if not data: 19 break 20 print(data.decode("utf-8")) 21 22 tcpCliSock.close()