Service-Side code:
1 ImportSocket2 3HOST ="'4PORT = 500075 6Sock_server =Socket.socket (socket.af_inet, socket. SOCK_STREAM)7 Sock_server.bind ((HOST, PORT))8 9Sock_server.listen (1)Ten One whileTrue: Aconn, addr =sock_server.accept () - - With Conn: the Print('Connected by', addr) - whileTrue: - Try: -data = CONN.RECV (1024) + Print("Server recv:", Conn.getpeername (), Data.decode ()) - if notData: + Break A at Conn.send (Data.upper ()) - Print("Send to Alex:", data) - exceptConnectionreseterror: - Break
Client 1 Code:
ImportSockethost='localhost'PORT= 50007Client=Socket.socket (socket.af_inet, socket. Sock_stream) Client.connect ((HOST, PORT)) whiletrue:msg= Input (">>>:"). Strip ()ifLen (msg) = =0:ContinueClient.sendall (Msg.encode ()) Data= CLIENT.RECV (1024) Print('Received', Data.decode ())
Client 2 Code:
1 ImportSocket2 3HOST ='localhost'4PORT = 500075 6Client =Socket.socket (socket.af_inet, socket. SOCK_STREAM)7 Client.connect ((HOST, PORT))8 9 whileTrue:Tenmsg = input (">>>:"). Strip () One ifLen (msg) = =0: A Continue - Client.sendall (Msg.encode ()) - thedata = CLIENT.RECV (1024) - - Print('Received', Data.decode ())
First open the server, and then turn on client 1, client 2, in the client 1 input information can receive server response information, in the client 2 input information can not receive server response information, at this time disconnect client 1, client 2 can receive the service side of the response information,
Client 1 run Result:
1 >>>: Client 12Received Client 13 >>>:4 Process finished with exit code 1
Client 2 run Result:
1 >>>: Client 22Received Client 23 >>>:
Server Run Results:
1Connected by ('127.0.0.1', 58852)2Server recv: ('127.0.0.1', 58852) Client 13Send To Alex:b'\XE5\XAE\XA2\XE6\X88\XB7\XE7\XAB\XAF1'4Connected by ('127.0.0.1', 58857)5Server recv: ('127.0.0.1', 58857) Client 26Send To Alex:b'\xe5\xae\xa2\xe6\x88\xb7\xe7\xab\xaf2'
python--Network Programming-----Socket Code Instance--Chat software upgrade version