Reputation: 402
I am working on a simple socket program which is supposed to measure the time it takes to transfer data over the network using various sizes of packets. The program runs fine until I want the server to respond to the client, telling the client that all data has been recieved. Below you will find the code:
Server:
def server():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1',6000))
s.listen(1)
con,addr=s.accept()
while 1:
data = con.recv(1024)
if not data:
break
print "Test"
con.send("Done")
con.close()
Client:
def client():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect(('127.0.0.1',6000))
data = ""
for j in range(0,1024):
data = data + "a"
start = int(time.time()*1000.0)
for i in range(0,15):
s.send(data)
data = s.recv(1024)
if data=="Done":
end = int(time.time()*1000.0)
s.close()
print str(end-start)+"ms"
As I said, the program runs fine until I try to respond from the server to the client. When the program comes to con.send("Done")
in the server and s.recv(1024)
in the cliet it stops, also the text "Test" is never printed in the server. If I remove con.send("Done")
and s.recv(1024)
in the client everything runs fine, and it runs fine if I remove the code to send the data from the client to the server as well, thus only sending data from the server.
I have been looking at examples, and I can't find any faulty code. So my question is why this doesn't work? And, also, do I even need the server to tell the client that it's done, or is there a more efficient way for the client to know when the server has recieved all the data?
Upvotes: 0
Views: 1173
Reputation:
What you need is threading or non-blocking connections. I just wrote a non-blocking TCP server that just runs out of the box. Here's an echo server:
from simpletcp.tcpserver import TCPServer
def echo(ip, queue, data):
queue.put(data)
server = TCPServer("localhost", 5000, echo)
server.run()
And here's what a client would look like:
from simpletcp.clientsocket import ClientSocket
s1 = ClientSocket("localhost", 5000, single_use=False)
response = s1.send("Hello, World!")
If you don't want to use that, there's always the built-in SocketServer.
Either way, there's no point in writing code that someone else has already written for you.
Upvotes: 0
Reputation: 43042
You either need nonblocking IO or threads. Otherwise read operations may block your program and thus prevent writes from making progress, or vice versa.
Upvotes: 1