標籤:int 訊息 sleep from new inf 開啟 ddr sock
# server.pyimport socketimport threadingimport times = socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.bind(('127.0.0.1',9999))s.listen(5)print('Waiting connection...')def tcp_link(sock,addr): print('Accept new data info from %s:%s...' %addr) # 首先向 用戶端發送 hello 訊息 sock.send(b'Welcome!') while True: data = sock.recv(1024) time.sleep(1) if not data or data.decode('utf-8') == 'exit': break sock.send(('Hello %s' %data.decode('utf-8')).encode('utf-8')) sock.close() print('connection %s:%s closed...' %addr) while True: # 等待用戶端發送訊息 sock, addr = s.accept() # 為每一個用戶端都單獨開啟一個線程 t = threading.Thread(target=tcp_link,args=(sock,addr)) t.start()
# custom.pyimport sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(('127.0.0.1',9999))print(s.recv(1024).decode('utf-8'))for data in [b'a',b'b',b'c']: s.send(data) print('received data %s' %s.recv(1024).decode('utf-8')) s.send(b'exit')s.close()
python socket 編程