I’ve been struggling along with sockets, making OK progress, but I keep running into problems, and feeling like I must be doing something wrong for things to be this hard.
There are plenty of tutorials out there that implement a TCP client and server, usually where:
- The server runs in an infinite loop, listening for and echoing back data to clients.
- The client connects to the server, sends a message, receives the same thing back, and then quits.
That I can handle. However, no one seems to go into the details of what you should and shouldn’t be doing with sequential communication between the same two machines/processes.
I’m after the general sequence of function calls for doing multiple messages, but for the sake of asking a real question, here are some constraints:
- Each event will be a single message client->server, and a single string response.
- The messages are pretty short, say 100 characters max.
- The events occur relatively slowly, max of say, 1 every 5 seconds, but usually less than half that speed.
and some specific questions:
- Should the server be closing the connection after its response, or trying to hang on to the connection until the next communication?
- Likewise, should the client close the connection after it receives the response, or try to reuse the connection?
- Does a closed connection (either through
close()or through some error) mean the end of the communication, or the end of the life of the entire object?- Can I reuse the object by connecting again?
- Can I do so on the same port of the server?
- Or do I have reinstantiate another socket object with a fresh call to
socket.socket()?
- What should I be doing to avoid getting ‘address in use’ errors?
- If a
recv()times out, is the socket reusable, or should I throw it away? Again, can I start a new connection with the same socket object, or do I need a whole new socket?
(clientsocket, address) = serversocket.accept()call. You can use the same port. (Think of webservers, they always accept connections to the same port, from thousands of clients)In both cases (closing or not closing), you should however have a message termination sign, for example a
\n. Then you have to read from the socket until you have reached the sign. This usage is so common, that python has a construct for that:socket.makefileandfile.readlineUPDATE:
UPDATE 2:
You should never assume that the connection is reliable, but include mechanisms to reconnect in case of errors. Therefore it is ok to try to use the same connection even if there are longer gaps.
As for errors you get: if you need specific help for your code, you should post small (but complete) examples.