Python中的TCP/IP套接字编程:如何使服务器在10秒后关闭连接



我需要使用python编写一个简单的程序(不允许线程(简单的请求/响应无状态服务器。客户发送请求,服务器响应响应。还需要处理多个交易这是我使用的简单:

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本机套接字库支持超时:

socket.setTimeout(value(

这样的事情应该有效:

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)

更高级别:https://docs.python.org/2/library/socketserver.html和https://docs.python.org/2/library/socketserver.html.

相关内容

最新更新