学习完 python 的协程处理,开始用 gevent 模块实现 socket 的服务端与多台客户端同时通信。
#Server import gevent,socket,sys from gevent import socket,monkey from gevent_socket_client import client monkey.patch_all() def server(host,port): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((host,port)) s.listen(500) while True: conn,addr = s.accept() # print(host,type(host)) name = conn.recv(1024).decode() print('%s is connected!'%name) conn.sendall(b'%s is connected!'%host.encode('utf-8')) gevent.spawn(handle_request,conn,addr,name) def handle_request(conn,addr,name): try: while True: data = conn.recv(1024) # print(addr[0],type(addr)) # msg = 'Recv from %s:'%addr[0],data.decode(encoding='utf-8') # msg = 'Recv from %s:' %name, data.decode(encoding='utf-8') print('Recv from %s:' %name, data.decode(encoding='utf-8')) # print(msg) conn.sendall(b'Done!') if not data: conn.shutdown(socket.SHUT_WR) except Exception as ex: print(ex) finally: conn.close()
#Client import socket def client(host,port,name): c = socket.socket(socket.AF_INET,socket.SOCK_STREAM) c.connect((host,port)) c.sendall(name.encode()) data = c.recv(1024) print(data.decode(encoding='utf-8')) while True: msg = bytes(input(">>:"),encoding="utf-8") c.sendall(msg) data = c.recv(1024) print(data.decode('utf-8')) c.close() if __name__ == '__main__': client('127.0.0.1',5580,'liu')