An example of Python socket programming: simulating various common winerror situations

example python socket programming simulating

One 、 introduction

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 .

Two 、C&S Code

here , Go straight to the code :

1. Code

Server program

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 = ('', 9999)
# Begin listen
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)
# Send some data to client
sendData = input("send:")
# Close the client socket
# Stop listen

Client program

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 = ('', 9999)
while True:
# Prompt input
sendData = input("send:")
if sendData == 'bye':
if len(sendData) > 0:
# Receive server data
recvData = tcpClientSocket.recv(1024)
print('recv:', recvData)
# Close socket

2. analysis

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 :)

3、 ... and 、 experiment

[WinError 10061] Because the target computer actively refuses , Unable to connect

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 connect Error of .

[WinError 10054] The remote host forced an existing connection to be closed

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

[WinError 10048] Usually every socket address ( agreement / network address / port ) Only one use is allowed

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 :

# It is amended as follows 

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

[WinError 10038] An operation was attempted on a non socket

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 
# 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, 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

... To be continued , Keep updating

If in the follow-up work , There are other interesting error messages , I'll also come here to keep updating :)

Four 、 summary

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:)

本文为[I've been to places that span an hour]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database