I've got a client-server app I'm making and I'm having a bit of trouble when the server wait for data from the client.
After my the client connects to the server socket, the server open him new thread and get data from the client (in JSON format). So far, my code works for a single message. When I added while loop, that always accept messages I got a problem. After some tests I found that the recv() function not waiting for new data and continues to the next line, and this is what creates the problem. I will be happy if you can help me fix the problem.
my receive data loop (The first iteration of the loop works but Receive data in the second iteration not wait for data and make problem because the next line not get any data)-
while True:
data = self.client.recv(self.size) # receive data
message = self.JSON_parser(data) # parser the data (data in json format)
process_message = processing.Processing(message[0]['key'],message[0]['user'],message[0]['data']) # send the receive data to the initialize process
process_return = process_message.action() # call to the action function
self.client.send(process_return) # send to the client message back
If recv()
is returning an empty string, it means that the connection has been closed.
The socket may be closed either by the client, or by the server. In this case, looking at the server code you posted, I'm almost sure that the client is closing the connection, perhaps because it's exiting.
In general, your server code should look like this:
while True:
data = self.client.recv(self.size)
if not data:
# client closed the connection
break
message = self.JSON_parser(data)
...
Bonus tip: a long JSON message may require more than one call to recv()
. Similarly, more than one JSON message may be returned by recv()
.
Be sure to implement buffering appropriately. Consider wrapping your socket into a file-like object and reading your messages line-by-line (assuming that your messages are delimited by newline characters).