我正在尝试在 python 中创建一个 tcplistener(必要时使用 pexpect)来侦听来自 windows xp 主机上 virtualbox 中 Ubuntu 的 tcp 连接。如果你们中的一个人能指出我正确的方向,我将不胜感激。谢谢你。
PS:我在这方面的经验有限,欢迎任何帮助。
我正在尝试在 python 中创建一个 tcplistener(必要时使用 pexpect)来侦听来自 windows xp 主机上 virtualbox 中 Ubuntu 的 tcp 连接。如果你们中的一个人能指出我正确的方向,我将不胜感激。谢谢你。
PS:我在这方面的经验有限,欢迎任何帮助。
Python 已经在标准库中提供了一个简单的套接字服务器,它被恰当地命名为SocketServer
. 如果您只需要一个基本的侦听器,请直接从文档中查看此示例:
import SocketServer
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.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "%s wrote:" % self.client_address[0]
print self.data
# just send back the same data, but upper-cased
self.request.send(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# 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()