PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

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

 October 22, 2022     python, sockets     No comments   

Issue

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()

Solution

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
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing