Recently, I used Python Wrote a little tool for testing , Maybe it works like this ：
This gadget works as a server , Request information from the client , Do something about it , Then return the message synchronously or asynchronously .
For this gadget , It mainly works as the server of the requested service . And in the development of this gadget , I often encounter things like Python Socket programming
[WinError XXXXX] Or something like that .
I've met a lot , I find , Instead of meeting a WinError Error and search for the reason , Let's write a simple one based on TCP The server-side client communication program of , Come and take these by yourself WinError The wrong situation is simulated , such , We're going to treat these as well WinError Mistakes have a deeper understanding .
Do what you say , First, the simplest use of Python Socket The server-side client communication program realized by programming . then , We build on this code , All kinds of operations , To simulate the implementation of some common WinError error .
here , Go straight to the code ：
""" Client side Author: Wang Ying Last modified: July 30 2019 """ from socket import socket, AF_INET, SOCK_STREAM # Create socket tcpSerSocket = socket(AF_INET, SOCK_STREAM) # Bind ip & port address = ('127.0.0.1', 9999) tcpSerSocket.bind(address) # Begin listen tcpSerSocket.listen(5) while True: # Receive client's connect, newSocket is served for client. # tcpSerSocket wait for another client's connect. newSocket, clientAddr = tcpSerSocket.accept() while True: # Receive client data recvData = newSocket.recv(1024) # if data length is 0, just break if len(recvData) > 0: print('recv:', recvData) else: break # Send some data to client sendData = input("send:") newSocket.send(bytes(sendData.encode('utf-8'))) # Close the client socket newSocket.close() # Stop listen tcpSerSocket.close()
""" Client side Author: Wang Ying Last modified: July 30 2019 """ from socket import socket, AF_INET, SOCK_STREAM # Create socket tcpClientSocket = socket(AF_INET, SOCK_STREAM) # Connect to server serAddr = ('127.0.0.1', 9999) tcpClientSocket.connect(serAddr) while True: # Prompt input sendData = input("send:") if sendData == 'bye': break if len(sendData) > 0: tcpClientSocket.send(bytes(sendData.encode('utf-8'))) else: break # Receive server data recvData = tcpClientSocket.recv(1024) print('recv:', recvData) # Close socket tcpClientSocket.close()
about Socket Programmatically , All languages are the same ,Python No exception . In this case ：
The server side program is bound with a 9999 port , Then listen to the client socket The connection of . The two floors here while loop , The outer layer is used to traverse the connection requests of multiple clients , The inner layer is used to realize the interaction with the client to receive and send data .
The client program connects to the server port , And then you go into a loop , Used to send data to the server .
here , First run the server side program , Then run the client program , The client sends the message first , Server received , Then the server sends the message to the client , Client received , The client can continue to send messages to the server … until , Client input bye, Then jump out of the loop , Close the client's socket Connect , And that's the end of the process .
This is a very simple server-side client communication program , We can use this program to simulate all kinds of WinError error . Let's start next ：）
We just said , Run this program , You need to run the server program first , Then run the client program , This is because the server monitors first , Then the client will connect to .
that , If the server program is not started first , At this point, the client runs , What kind of mistakes will happen ？
Sum up ：
Once the client starts , The server does not want to connect on the client side IP And port number , Then there will be
[WinError 10061] Because the target computer actively refuses , Unable to connectError of .
Let's run the server program first , Then run the client program , And then the client program will be forced to kill （ Don't let it shut down properly socket Connect ）, What kind of mistakes will occur at this time ？
This mistake is easy to understand , Connected to socket The connection is forcibly interrupted by the other party （ abnormal close Dropped ）, This error will appear .
Some netizens may feel that , Here is the client force kill , So what's wrong with killing the server ？ ha-ha , You can try it yourself , The answer is no mistake ：） why , You can think for yourself , Here's just a hint , A client only connects to one server , But a server , It is to connect zero one or more clients .
Sum up ：
When the client connects to the server , The client program is forced to kill , At this point, the server will report an error
[WinError 10054] The remote host forced an existing connection to be closed
Let's modify the client code a little bit , Try not to let the client go connect Server side socket Connect , It is bind（ It's like the server ）, Revised as follows ：
tcpClientSocket.connect(serAddr) # It is amended as follows tcpClientSocket.bind(serAddr)
What's the problem ？
In fact, this is also very easy to understand , After all, the same port is monitored by two programs , There is bound to be a port occupancy problem .
Sum up ：
A port has been occupied , And then another program wants to use it , There will be errors
[WinError 10048] Usually every socket address ( agreement / network address / port ) Only one use is allowed
We're going to change the code this time , This time we modify the server-side code ：
while True: ... # 2. This call close, Leading to the next cycle recv Of # When you use a closed socket Connect # Receive data newSocket.close() # 1. It should have been closed after jumping out of the loop socket, We are now # After receiving the client's return , Shut it down immediately . Analog off # close socket And then receive socket Data scenario . # newSocket.close()
What we modified is server.py, The original close The function is put inside the loop , Lead to close Then I call once recv. Let's run the server program first , Then run the client program to see what happens ：
We found that , On the server side, the program runs to recv When it comes to
[WinError 10038] An operation was attempted on a non socket Error of , Actually, it's easy to understand , Because after all, you've put this socket The connection is closed , And then you want to use it to receive data .
To sum up ：
When you shut down a socket Connect （close）, And then use that socket Object receives data （recv）, There will be an error
[WinError 10038] An operation was attempted on a non socket
If in the follow-up work , There are other interesting error messages , I'll also come here to keep updating ：）
Study Python Ben is a very happy thing , Happier than it is , That's using Python The process of .
Python The way , The road is long but not boring ~~~
To be Stronger：）