socket并发聊天
server端:
import socketserver
class MyServer(socketserver.BaseRequestHandler): #创建一个类,继承socketserver里面的BaseRequestHandler类
def handle(self): #方法名称是固定的,handle里面放置服务器端通信逻辑
print("服务端启动...")
while True:
conn = self.request #获取客户端通道
print(self.client_address)#获取客户端IP和端口
while True:
client_data=conn.recv(1024) #接收客户端发送的数据
print(str(client_data,"utf8"))
#print("waiting...")
conn.sendall(client_data)
conn.close()
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1',8091),MyServer) #创建一个ThreadingTCPServer类的对象,这个类里面定义了socket对象创建、服务器端地址绑定和客户端Listen监听设置
server.serve_forever() #调用server对象的serve_forever方法,方法里面定义了调用MyServer的handle方法
server.handle_request()
client端:
import socket
ip_port = ('127.0.0.1',8091)
sk = socket.socket()
sk.connect(ip_port)
print ("客户端启动:")
while True:
inp = input('>>>')
if inp == 'exit':
break
sk.sendall(bytes(inp, "utf8"))
server_response=sk.recv(1024)
print(str(server_response,"utf8"))
sk.close()