Python网络编程Socket之协程
一、服务端
1 __author__ = "Jent Zhang" 2 3 import socket 4 import gevent 5 from gevent import monkey 6 7 monkey.patch_all() # 把当前程序中的所有IO操作单独做上标记 8 9 10 def server(port): 11 s = socket.socket() 12 s.bind(("0.0.0.0", port)) 13 s.listen(5000) 14 while True: 15 conn, addr = s.accept() 16 gevent.spawn(handle_request, conn) 17 18 19 def handle_request(conn): 20 try: 21 while True: 22 data = conn.recv(1024) 23 print(data.decode("utf8")) 24 conn.send(data.upper()) 25 if not data: 26 conn.shutdowm(socket.SHUT_WR) 27 28 except Exception as ex: 29 print(ex) 30 finally: 31 conn.close() 32 33 34 if __name__ == "__main__": 35 server(8001)
二、客户端
1 __author__ = "Jent Zhang" 2 3 import socket 4 5 HOST = "localhost" 6 PORT = 8001 7 8 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 s.connect((HOST, PORT)) 10 11 while True: 12 msg = bytes(input(">>:"), encoding="utf8") 13 if not msg: continue 14 s.sendall(msg) 15 data = s.recv(1024) 16 17 print("Received", repr(data.decode("utf8"))) 18 19 s.close()
好记性不如烂笔头!