The first thing to note is that socket programming is not recorded here, it only analyzes the handling of several special exceptions in the most simple socket programming chat room. the first thing to note is that it does not record very profound socket programming, the code is as follows:
Server:
Import socketHOST = "" PORT = 8870sk = socket. socket (socket. AF_INET, socket. SOCK_STREAM) sk. bind (HOST, PORT) sk. listen (5) while True: print ("server startup") conn, addr = sk. accept () print (addr) while True: try: server_recv_data = conn. recv (1024) # if exit is entered on the client, no blocking is performed here, but the received information is empty. # if exit is entered on the client, press the Enter key, if len (server_recv_data) = 0: print ("null received") break failed t ConnectionResetError as err: print (err) break print (str (server_recv_data, encoding = "UTF-8") server_resp_data = input (">>>") conn. sendall (bytes (server_resp_data, encoding = "UTF-8") conn. close () sk. close ()
Client:
Import socketHOST = "127.0.0.1" PORT = 8870sk = socket. socket () sk. connect (HOST, PORT) print ("start the client... ") while True: indium = input (" >>> ") if indium =" exit "or not indium: # What needs to be noted here is, when you press enter directly on the client, the enter key is blank. sendall (bytes (indium, encoding = "UTF-8") server_response = sk. recv (1024) print (str (server_response, encoding = "UTF-8") sk. close ()
Note:
1. when the client is forcibly disabled (for example, when you press the stop button on the left side of the debugging window in pycharm), the client certainly reports an error, but on Linux, the server does not report an error, only the received information is null, that is, server_recv_data is null. Therefore, the server makes a judgment to exit the inner loop so that it can connect to other clients to send connection requests;
2. when the client enters exit to exit the current chat, if the client determines that break exits, the key is that the server obtains the result that server_recv_data is empty, which is the same as the above;
3. unique server -- recv_data = conn. recv (1024) is blocked: the client directly press the Enter key. in this case, the server is still waiting for the client to send the message (it is considered that no information has arrived), and the client cannot send the message again, because you have already press enter, you can enter the information again, but you cannot send it (even if you press enter again), so to solve this problem, by default, we think that when the client performs this action, it indicates that it wants to exit. in this case, the "if not P:" statement is made on the client, and the "exit chat" function is null, continue waiting for other connections after break