0

I need to write a simple program (no thread allowed) using Python for a simple request/response stateless server. client sends a request and server responds with a response. Also it needs to handle multiple transaction This is the simple one I am using:

import asyncore, socket

class Server(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(('', port))
        self.listen(1)

    def handle_accept(self):
        # when we get a client connection start a dispatcher for that
        # client
        socket, address = self.accept()
        print 'June, Connection by', address
        EchoHandler(socket)

class EchoHandler(asyncore.dispatcher_with_send):
    # dispatcher_with_send extends the basic dispatcher to have an output
    # buffer that it writes whenever there's content
    def handle_read(self):
        self.out_buffer = self.recv(1024)
        if not self.out_buffer:
            self.close()

s = Server('', 5088)

syncore.loop(timeout=1, count=10)


import asyncore, socket

class Client(asyncore.dispatcher_with_send):
    def __init__(self, host, port, message):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))
        self.out_buffer = message

    def handle_close(self):
        self.close()

    def handle_read(self):
        print 'June Received', self.recv(1024)
        self.close()

c = Client('', 5088, 'Hello, world')
asyncore.loop(1)
1
  • 1
    There's a timeout parameter to asyncore.loop(), it seems like this would be useful. Commented Jun 29, 2017 at 22:40

1 Answer 1

2

Pythons native socket library supports timeouts out of the box:

socket.settimeout(value)

So something like this should work:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 12345))
sock.listen(1)

conn, addr = s.accept()
conn.settimeout(10)

A bit more high level: https://docs.python.org/2/library/socketserver.html and https://docs.python.org/2/library/socketserver.html#socketserver-tcpserver-example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.