# coding: utf-8 import socket messages = ['This is the message ', 'It will be sent ', 'in parts ', ] server_address = ('localhost', 8090) # Create aTCP/IP socket socks = [socket.socket(socket.AF_INET, socket.SOCK_STREAM), socket.socket(socket.AF_INET, socket.SOCK_STREAM), ] # Connect thesocket to the port where the server is listening print ('connecting to %s port %s' % server_address) # 连接到服务器 for s in socks: s.connect(server_address) for index, message in enumerate(messages): # Send messages on both sockets for s in socks: print ('%s: sending "%s"' % (s.getsockname(), message + str(index))) s.send(bytes(message + str(index)).decode('utf-8')) # Read responses on both sockets for s in socks: data = s.recv(1024) print ('%s: received "%s"' % (s.getsockname(), data)) if data != "": print ('closingsocket', s.getsockname()) s.close()
写代码过程中遇到了两个问题, 一是如何判断客户端已经关闭了socket连接, 后来自己分析了下, 如果关闭了客户端socket, 那么此时服务器端接收到的data就是'', 加个这个判断。二是如果服务器端关闭了socket, 一旦在调用socket的相关方法都会报错, 不管socket是不是用不同的容器存储的(意思是说list_1存储了socket1, list_2存储了socket1, 我关闭了socket1, 两者都不能在调用这个socket了)
服务器端:
客户端: