0

Here follow a simple python server using socket module:

import socket
import sys
HOST = ''
PORT = 8008
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
    s.bind((HOST,PORT))
except socket.error as msg:
    print 'Bind failed. Error code : %s , Message : %s'%(msg[0],msg[1])
    sys.exit()
print 'Socket bind complete!'
s.listen(10)
socket.setdefaulttimeout(3)
l = set()
while True:
    try:
        a = s.accept()
        print 'Connected with %s:%d'%a[1]
        l.add(a)
    except:
        print 'Accept error!'
    for a in l:
        b = a[0].recv(4096)
        if b:
            print 'From %s:%d'%a[1]+' recv: %s'%b

It was correct at the first time(connection by client), BUT the program stuck at the second time.

Socket bind complete!
Connected with 127.0.0.1:52093
From 127.0.0.1:52093 recv: aasdf
_
(STUCK)

What was wrong? Please point out the problem for me

2
  • What did you change between the first and second time? Commented Oct 15, 2014 at 7:46
  • I am sorry I was not clear. I mean the second connection by client. Commented Oct 15, 2014 at 7:48

1 Answer 1

1

At first glance it looks like your program will endlessly hang trying to read from the first socket you open, if creating another.

  1. You accept one connection, save it in an unordered set (kinda strange type to use)
  2. recv() blocks on the one connection until data is available, but it prints it out when it gets it.
  3. You accept another connection
  4. The first connection (randomly) comes up in your for loop, and you attempt to recv() from it, which blocks forever.

Using the select module would be prudent if you want to wait on multiple sockets.

Other things, % formatting is ugly and deprecated in Python 3 use .format(), which has been in Python since 2.6.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.