Reputation: 11
Maybe I am not understanding how sockets are supposed to work, so perhaps someone can help me. I though that the following would loop forever printing "Sent Hello. Received: Hello to you!", but in fact it loops twice and then hangs. No timeout, connection reset by peer, etc. Just hangs.
import socket
socket_list = []
for i in range(60000, 60002):
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect("",i)
socket_list.append(soc)
while True:
for soc in socket_list:
soc.sendall("Hello.")
msg = soc.recv(1024)
print "Sent Hello. Received:",msg
The code on the other end of the connection is simply:
import socket
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.bind("localhost",6000x)
while True:
soc.listen(1)
conn, addr = soc.accept()
msg = conn.recv(1024)
if msg == "Hello":
conn.sendall("Hello to you!")
Upvotes: 1
Views: 253
Reputation: 362157
for i in range(60000, 60002):
soc.connect("",i)
In the client program you open two sockets at startup and then use those sockets for the lifetime of your program.
while True:
conn, addr = soc.accept()
In the server program you repeatedly accept()
a new connection every iteration of the main loop. This successfully accepts the first connection on each port, performs one recv/send cycle, then starts over and tries to accept a new connection rather than continue using the existing socket.
One of the programs needs to change. Either your client program needs to call socket()
and connect()
inside its while loop, or your server program needs to move its listen()
and accept()
calls outside of its while loop.
Upvotes: 1