python socketserver connection timeout -
i new python socket programming. trying create simple chat application trying send data client program server in server program while receiving data encountering "timed out"
my client program-
import socket port = 3017 def handler(req): s = socket.socket(socket.af_inet, socket.sock_stream) try: s.connect(("localhost", port)) except socket.error, msg: print("error connecting socket") s = none finally: f.close() s.settimeout(10.0) s.send(req) line = s.recv(1024) s.close() return line if __name__ == '__main__': while(1): input = raw_input(">") resp = handler(input) print resp
my server program-
import socket import socketserver class echo_server(socketserver.streamrequesthandler): def handle(self): timeout_telnet = float(2.0) self.connection.settimeout(timeout_telnet) data = [] # read in lines. while 1: try: line = self.rfile.readline() except baseexception, e: # timeout. print("error", e) break data.append(line) print("data in handle method-\n", data) self.wfile.write(("echo data- ".join(data))) break # goodbye def main(): s = socketserver.threadingtcpserver(("", 3017), echo_server) try: s.serve_forever() except keyboardinterrupt: print("shutting down.") s.socket.close() if __name__ == "__main__": main()
your problem because need control messages length when using stream-sockets.
what happends there:
your client sending data (n bytes). server reading data socket, not know "message" complete or additional data sent.
what can do? if replace
self.rfile.readline()
with self.request.recv(10) - server read 10 bytes , send them back. can set message size messages server , client sending each other.
also usefull info here: https://docs.python.org/2/howto/sockets.html#using-a-socket
here example of simplest chat:
client
def handler(req): s = socket.socket(socket.af_inet, socket.sock_stream) s.connect(("localhost", port)) message = req s.send(req) print s.recv(1024) s.close()
server
def handle(self): while true: line = self.request.recv(1024) if line: print("data in handle method-\n", line.strip()) self.wfile.write(line)
but face problens later , python documentation can understanding how works.
Comments
Post a Comment