Why does my socket client stall after sending the first message?

Question:

I am trying to make a socket client in python. I can send the first message, with no errors, but when I try to send the second one, it stalls.

import socket , time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def OpenConnection(IP,PORT):
    global sock    
    sock.connect((IP, PORT))
def SendMessage(StringMessage):
    global sock
    print "Step 1"
    sock.send(StringMessage)
    print "Step 2"
    reply = sock.recv(1024)  # limit reply to 1024K
    print StringMessage
    return reply
def CloseConnection():
    global sock
    sock.close()
HOST, PORT = 'localhost', 34567
OpenConnection(HOST,PORT)
print SendMessage('test1')
print "Sleep for 3"
time.sleep(3)
print "Sendind Second Message.."
print SendMessage('test2')
CloseConnection()
Asked By: user2136174

||

Answers:

Your code works for me – is the server you’re connecting to sending anything back? I used netcat to listen on port 34567. Here is the server output after first running your program:

$ nc -l 34567
test1

And here is the client

$ python socktimeout.py
Step 1
Step 2

At this point the client is waiting in the sock.recv(1024) call for a response from the server. Typing a message (“TEST” say) and hitting enter in the server window allows the code to proceed. Now the server looks like this:

$ nc -l 34567
test1TEST
test2

And the client:

$ python socktimeout.py
Step 1
Step 2
test1
TEST

Sleep for 3
Sendind Second Message..
Step 1
Step 2

Again typing a message and pressing enter will allow your program to complete and close the connection.

Note that pressing enter is only required as netcat is line buffering the input, if your server was sending back data using some other process, it is not a requirement to append a line ending to the message (although it might be a good idea, depending on your protocol).

EDIT

Here is the final server state after sending back another message:

$ nc -l 34567
test1TEST
test2TEST
$

And here is the client:

$ python socktimeout.py
Step 1
Step 2
test1
TEST

Sleep for 3
Sendind Second Message..
Step 1
Step 2
test2
TEST

$
Answered By: Peter Gibson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.