When the socket to send and receive an error, I would simply assume that the network is broken (or server is down), the socket closed, and then have been trying to connect, even after the continue to communication, according to online data, socket don't know whether still attached, use the code to judge, so I use a simple conn_ok to tag is connected,
Now the question is: under the condition of the server online, the client can even on it, after turn off the server, a socket is an error and the error can be captured, capture the error after I do close then take conn_ok reset once, should can to try to connect server socket, but on the reconnection here was an error: attempt to connect already - connected SSLSocket! , what? The socket is connected to? Not have call close ()? Online and socket. The close () is not immediately shut down, we would like to have to shutdown immediately shut down, and after, still the same,
Simplify the question: who knows how to put the SSL socket gracefully disconnect after packaging, and then to make the connection?
The code is as follows:
Def send_info_to_server (IP, port, q) :
CA_FILE='cert'
KEY_FILE='pkey'
CERT_FILE='cert'
The context=SSL. SSLContext (SSL. PROTOCOL_TLSv1)
The context. Check_hostname=False
The context. Load_cert_chain (certfile=CERT_FILE, keyfile=KEY_FILE)
The context. Load_verify_locations (CA_FILE)
# establish a socket connection with the server
With the socket. The socket () as the sock:
With the context. Wrap_socket (sock, server_side=False) as ssock:
Ssock. Settimeout (0.1) # 0.1 overtime, in order to avoid blocking in the recv (in some cases, the client to the server data, the server does not return response information)
Conn_ok=False
While True:
While not conn_ok: # if not connected to the server, every 5 seconds to attempt a
Try:
Ssock. Connect ((IP, port))
Except the socket. Gaierror as e:
Print (' Address - related error connecting to the server: % s' % e)
Time. Sleep (5)
Except the socket. The error as e:
Print (' Connection error: % s' % e)
Time. Sleep (5)
The else:
Print (' Conntected to: % s' % IP)
Conn_ok=True
# send information to the server
Try:
MSG=(' do I connect with the server? ')
MSG=wrap_info (MSG). Encode (" utf-8 ")
Ssock. Send (MSG)
Except the socket. The error as e:
Print (' Send message error: % s' % e)
Ssock. Shutdown (socket. SHUT_RDWR)
Ssock. Close ()
Conn_ok=False
The else:
Print (' Sent a message: ', MSG)
# receiving server returned information
Try:
Buf=ssock. Recv (1024). The decode (" utf-8 ")
If not buf:
The continue
Except the socket. The error as e:
Ssock. Shutdown (socket. SHUT_RDWR)
Ssock. Close ()
Print (' Read the message error: % s' % e)
Conn_ok=False
The else:
Print (f "receive MSG from server: {buf}")
Time. Sleep (1)
Ssock. Close ()
If __name__=="__main__ ':
Send_info=threading. Thread (target=send_info_to_server, args=(CFG [' server_ip], int (CFG) [' server_port], info_que))
Send_info. Start ()
Send_info. The join ()