Reputation: 65
I am new to python socket programming. I am trying to create a simple chat application I am trying to send data from client program to server but in server program while receiving the data I am 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 all the 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()
Upvotes: 4
Views: 2255
Reputation: 948
Your problem is because you need to control messages length when you are using stream-sockets.
What happends there:
Your client sending some data (N bytes). Your server reading data from socket, but it does not know is your "message" complete or some additional data will be sent.
What can you do? If you will replace
self.rfile.readline()
with self.request.recv(10) - your server will read 10 bytes and will send them back. So you can set some message size for messages your server and client will be sending to each other.
Also some usefull info is here: https://docs.python.org/2/howto/sockets.html#using-a-socket
Here is 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 probably you will face some problens later and python documentation can help you with understanding how does it works.
Upvotes: 2
Reputation: 65
The real problem was that server was waiting for more message to be sent from client which caused timeout. I have found a solution which is working In the client program add this line
s.shutdown(1)
after
s.send(req)
and in server program replace
line = self.rfile.readline()
with
line = self.request.recv(1024)
shutdown(1) tells the server “This client is done sending, but can still receive.”
Upvotes: 0