When you create a file () on a socket and then use readlines () on it, it will continue until you reach the end of the file, which in the case of a socket is closed at the other end.
Using makefile () in this case does not make any sense to me, especially since you create and close it after each command. Just use send () and recv () at both ends.
You probably also want to have some kind of actual “protocol”, so the server tells the client “HERE TO ACCEPT RESPONSE” and “THIS IS THE END OF RESPONSE” so that the client knows. Otherwise, it becomes difficult to know when to stop waiting for an answer. :)
Update with an example that works:
server.py:
import sys, os, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 50500)) print("Server started") s.listen(1) while True: print "Accepting" conn, addr = s.accept() print 'New connection from ', addr while True: try: rc = conn.recv(1024) print "Command", rc if not rc.strip(): continue if rc.strip() == 'END': print "Close" conn.send("**END**") conn.close() break else: conn.send("This is the result of command %s\n" % rc) except Exception: conn.close() sys.exit()
client.py
import sys, os, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost', 50500)) while True: cmd = raw_input('$ ') s.send(cmd) result = s.recv(1024) print result if result == "**END**": print "Ending" break
Lennart Regebro
source share