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
asked Oct 15, 2014 at 7:43
colinzcli
811 gold badge1 silver badge10 bronze badges
-
What did you change between the first and second time?Nick T– Nick T2014年10月15日 07:46:06 +00:00Commented Oct 15, 2014 at 7:46
-
I am sorry I was not clear. I mean the second connection by client.colinzcli– colinzcli2014年10月15日 07:48:26 +00:00Commented Oct 15, 2014 at 7:48
1 Answer 1
At first glance it looks like your program will endlessly hang trying to read from the first socket you open, if creating another.
- You accept one connection, save it in an unordered set (kinda strange type to use)
recv()blocks on the one connection until data is available, but it prints it out when it gets it.- You accept another connection
- The first connection (randomly) comes up in your
forloop, and you attempt torecv()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.
answered Oct 15, 2014 at 7:56
Nick T
27k14 gold badges88 silver badges128 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py