Reputation: 12294
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:
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:
and some specific questions:
close()
or through some error) mean the end of the communication, or the end of the life of the entire object?
socket.socket()
?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?Upvotes: 3
Views: 931
Reputation: 2333
(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.makefile
and file.readline
UPDATE:
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.
Upvotes: 2