import gevent from gevent import socket,monkey monkey.patch_all() def server(port): s = socket.socket() s.bind(('0.0.0.0', port)) s.listen(500) while True: cli, addr = s.accept() # socket會建立一個線程連接,這裏會交給協程處理 # 連接後經過gevent啓動一個協程 # 接收一個函數,與連接實例參數 gevent.spawn(handle_request, cli) # 全部交互都由handle處理 def handle_request(conn): try: while True: data = conn.recv(1024) print("recv:", data) conn.send(data) if not data: # 若是沒有數據就關閉Client端 conn.shutdown(socket.SHUT_WR) # 若是出現異常就打印異常 except Exception as ex: print(ex) # 最後中斷實例的conn finally: conn.close() if __name__ == '__main__': server(8001)
import socket # 連接服務端 HOST = 'localhost' # The remote host PORT = 8001 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) # 數據請求 while True: msg = bytes(input(">>:"),encoding="utf8") s.sendall(msg) data = s.recv(1024) #print(data) # repr格式化輸出 print('Received', repr(data)) s.close()