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

时间:2017-06-29 22:36:37

标签: python sockets tcp asyncore

我需要使用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)

1 个答案:

答案 0 :(得分:2)

Pythons本机套接字库支持开箱即用的超时:

socket.settimeout(值)

所以这样的事情应该有效:

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.htmlhttps://docs.python.org/2/library/socketserver.html#socketserver-tcpserver-example