1. Directly on the code
server:__author__='Alex'#Coding:utf-8ImportSocketip_port= ('127.0.0.1', 8000) SK=socket.socket () sk.bind (ip_port) sk.listen (5)Print("Server start ...") whiletrue:conn,addr=sk.accept () whileTrue:Try: Recv_data= Conn.recv (1024) ifLen (recv_data) = = 0: break exceptException as E:Print("accidental Interruption") break Print(str (recv_data,"UTF8")) Send_data= Input (">>>>>>") Conn.sendall (bytes (send_data,"UTF8") ) Conn.close ()
######################################################## #client:__author__='Alex'#Coding:utf-8ImportSocketip_port= ('127.0.0.1', 8000) SK=socket.socket () sk.connect (ip_port)Print("client-initiated ...") whileTrue:send_data= Input (">>>>>>>") ifSend_data = ='Exit': breaksk.send (bytes (send_data,"UTF8")) Recv_data= Sk.recv (1024) Print(str (recv_data,"UTF8") ) Sk.close ()
In this program to do a few notes: 1, if the client sends exit, then the server will receive an empty string, because you can determine the length of the received string to know whether the client exits, 2, if the client is terminated by the way the program is closed, Then the server will receive a exception, then the service side to do the exception handling (in the Windows environment), in the case of linux, the termination of the program will cause the service side to receive an empty String.
Python Socket Programming