標籤:set ror error ted bin list decode span 升級版
服務端代碼:
1 import socket 2 3 HOST = ‘‘ 4 PORT = 50007 5 6 sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 sock_server.bind((HOST, PORT)) 8 9 sock_server.listen(1)10 11 while True:12 conn, addr = sock_server.accept()13 14 with conn:15 print(‘Connected by‘, addr)16 while True:17 try:18 data = conn.recv(1024)19 print("server recv:", conn.getpeername(), data.decode())20 if not data:21 break22 23 conn.send(data.upper())24 print("send to alex:", data)25 except ConnectionResetError:26 break
用戶端1代碼:
import socketHOST = ‘localhost‘PORT = 50007client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client.connect((HOST, PORT))while True: msg = input(">>>:").strip() if len(msg) == 0: continue client.sendall(msg.encode()) data = client.recv(1024) print(‘Received‘, data.decode())
用戶端2代碼:
1 import socket 2 3 HOST = ‘localhost‘ 4 PORT = 50007 5 6 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 client.connect((HOST, PORT)) 8 9 while True:10 msg = input(">>>:").strip()11 if len(msg) == 0:12 continue13 client.sendall(msg.encode())14 15 data = client.recv(1024)16 17 print(‘Received‘, data.decode())
先開啟服務端,然後開啟用戶端1,用戶端2,在用戶端1輸入資訊能夠收到服務端的響應資訊,在用戶端2輸入資訊不能收到服務端的響應資訊,此時斷開用戶端1 的串連,用戶端2可以正常收到服務端的響應資訊,
用戶端1運行結果:
1 >>>:用戶端12 Received 用戶端13 >>>:4 Process finished with exit code 1
用戶端2運行結果:
1 >>>:用戶端22 Received 用戶端23 >>>:
服務端運行結果:
1 Connected by (‘127.0.0.1‘, 58852)2 server recv: (‘127.0.0.1‘, 58852) 用戶端13 send to alex: b‘\xe5\xae\xa2\xe6\x88\xb7\xe7\xab\xaf1‘4 Connected by (‘127.0.0.1‘, 58857)5 server recv: (‘127.0.0.1‘, 58857) 用戶端26 send to alex: b‘\xe5\xae\xa2\xe6\x88\xb7\xe7\xab\xaf2‘
Python--網路編程-----socket代碼執行個體--聊天軟體升級版