使用python socketserver在同一个套接字连接下允许多个请求

问题描述 投票:0回答:1

我在 Python 中启动了一个 TCP 服务器,并尝试使用单个套接字连接向其发送多个请求:

>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('127.0.0.1', 4444))
>>> message = b'hi'
>>> s.sendall(message)
>>> resp = s.recv(4096)
>>> resp
b'hello'
>>> # Now trying to send another message without restarting the socket
>>> s.sendall(message)
>>> resp = s.recv(4096)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

服务器拒绝了我的第二个请求,我必须关闭并重新启动套接字,以便我可以发送新请求。

这就是我的服务器的样子:

import socketserver
class MyTCPServer(socketserver.BaseRequestHandler):
    def handle(self):
        message = self.request.recv(4096)
        self.request.sendall(b'hello')

server = socketserver.TCPServer(('127.0.0.1', 4444), MyTCPServer)
server.serve_forever()

如何使服务器保持连接处于活动状态,从而使用单个套接字接受多个请求?

python tcpserver socketserver
1个回答
0
投票

也许这是 Windoze 的事情。这是一个示例,展示了如何将同一个连接的套接字用于多个发送/接收序列。

不是意味着代表健壮的适合生产的代码:

from socket import socket, AF_INET, SOCK_STREAM
from socketserver import BaseRequestHandler, TCPServer
from threading import Thread

HOST = "localhost"
PORT = 10101
ADDR = HOST, PORT
RECVBUF = 4096

class MyHandler(BaseRequestHandler):
    def handle(self):
        while self.request.recv(RECVBUF):
            self.request.sendall(b"Hello world!")

def server(tcpserver):
    tcpserver.serve_forever()

def echo():
    with socket(AF_INET, SOCK_STREAM) as s:
        s.connect(ADDR)
        for _ in range(5): # do this multiple times with the same conencted socket
            s.sendall(b"Some dummy data")
            print(s.recv(RECVBUF).decode())

if __name__ == "__main__":
    with TCPServer(ADDR, MyHandler) as tcpserver:
        (t := Thread(target=server, args=[tcpserver])).start()
        echo()
        tcpserver.shutdown()
        t.join()

输出:

Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
© www.soinside.com 2019 - 2024. All rights reserved.