gpt4 book ai didi

Python socketserver,如何获取自己的tcp端口号

转载 作者:可可西里 更新时间:2023-11-01 02:34:28 39 4
gpt4 key购买 nike

我需要用socketserver搭建一个tcp server。根据他们的文档,我需要继承类 TCPServer,并将它传递给类 BaseRequestHandler 的子类,我重写了方法 handle()。

现在我需要在不同的端口上构建两个服务器,有没有办法在 handle() 函数中,(否则我必须设置两个几乎相同的处理程序类,这不是我想要的),我可以得到我自己的端口号?

最佳答案

不要在handle() 方法中执行,将端口号传入(来自https://docs.python.org/2/library/socketserver.html#socketserver-tcpserver-example ):

#!/usr/bin/env python

import SocketServer, argparse

class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.

It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""

def handle(self):
# self.server.server_address is a tuple (IP, port) the server is listening on
(host, port) = self.server.server_address
print 'port # is: {}'.format(port)
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', required=True, help='the TCP port to listen on')
args = parser.parse_args()
HOST, PORT = "localhost", int(args.port)

# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()

在此示例中,您必须在使用 -p 命令行开关启动程序时提供端口号作为参数。

关于Python socketserver,如何获取自己的tcp端口号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33619430/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com