I'm learning today python when , There's a problem , It's a simple question , But there are many answers on the Internet , uneven , It's useful try-expect Calling the function repeatedly , And settings response.close(), These are all the answers I feel , Next, I summarized the problems I encountered :
Today, I wrote a book with socket A script that connects the client and server scripts , The main function is that the client sends commands to the server , Then the server executes , After execution, the server returns the execution result to the client . But give me an error :
TimeoutError: [WinError 10060] Because the connector did not reply correctly after a period of time or the connected host did not respond , Connection attempt failed .
Check the reason for the error report , The request timed out , You need to add a timeout parameter timeout, Creating socket Front settings :
import socket
socket.setdefaulttimeout(500)
No error is reported after setting , It's all a small problem . As a result, he was not happy and reported another mistake to me !!
Continue to find solutions online , As a result, many people say that the crawler is recognized by the server , The server closes this socket Connect . But this is my own server ! The code on my server does not close this socket Connect , Why would you report this mistake .
Because the problem location is not clear , I searched the Internet for a long time , Finally found this blog :Python+socket Perfect implementation TCP Long connections remain alive
Used in network development TCP When the protocol realizes the communication between the client and the server , In some cases, it is necessary to maintain a long connection , By default , When there is no data receiving / sending operation after a certain period of time , The connection will automatically disconnect , This leads to data loss .
The client is creating socket after , Set the heartbeat :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)
sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 60 * 1000, 30 * 1000))