简体   繁体   中英

TCP/IP Socket programming in Python: how to make server close the connection after 10 seconds

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM