我正在尝试使用socketserver
在Python 3.6.7中编写一个TCP服务器,该服务器侦听同一IP地址上的两个端口。这是我到目前为止想出的:
import socketserver
class TCPServer(socketserver.StreamRequestHandler):
def handle(self):
self.data = self.rfile.readline().strip()
print(str(self.data))
if __name__ == "__main__":
HOST = "localhost"
DATA_PORT = 64000
CONTROL_PORT = 64001
data_server = socketserver.TCPServer((HOST, DATA_PORT), TCPServer)
control_server = socketserver.TCPServer((HOST, CONTROL_PORT), TCPServer)
try:
while True:
data_server.handle_request()
control_server.handle_request()
except KeyboardInterrupt:
data_server.server_close()
control_server.server_close()
然后我尝试使用以下客户端与服务器对话:
import socket
from time import sleep
HOST = "localhost"
DATA_PORT = 64000
CONTROL_PORT = 64001
data = "test data"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock_d, socket.socket(
socket.AF_INET, socket.SOCK_STREAM
) as sock_c:
sock_d.connect((HOST, DATA_PORT))
sock_c.connect((HOST, CONTROL_PORT))
for cnt in range(5):
sock_d.sendall(bytes(data + " " + str(cnt) + "\n", "utf-8"))
print("Sent: {}".format(cnt))
sock_c.sendall(bytes(data + " " + str(cnt + 1) + "\n", "utf-8"))
print("Sent: {}".format(cnt + 1))
sleep(1)
发生的是,在客户端,我得到以下输出:
Sent: 0
Sent: 1
Sent: 1
Sent: 2
Traceback (most recent call last):
File "<...> client_test.py", line 15, in <module>
sock_d.sendall(bytes(data + " " + str(cnt) + "\n", "utf-8"))
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
在服务器上时,我只会得到:
b'test data 0'
b'test data 1'
有人可以帮我指出我在这里想念的东西吗?