【问题标题】:Using pexpect to listen on a port from a virtualbox使用 pexpect 监听来自 virtualbox 的端口
【发布时间】:2010-09-10 05:11:07
【问题描述】:

我正在尝试在 python 中创建一个 tcplistener(必要时使用 pexpect)来侦听 windows xp 主机上 virtualbox 中来自 Ubuntu 的 tcp 连接。如果你们中的一个人能指出我正确的方向,我将不胜感激。谢谢。

P.S:我在该领域的经验有限,欢迎任何帮助。

【问题讨论】:

  • 如果您能回答以下问题,将会有所帮助:您的代码在哪里运行? Windows 主机还是 Ubuntu 来宾?为什么你认为 pexpect 是必要的?简而言之,您想要完成什么?

标签: python tcp port tcplistener pexpect


【解决方案1】:

Python 已经在标准库中提供了一个简单的套接字服务器,它被恰当地命名为SocketServer。如果您只需要一个基本的监听器,请查看example straight from the documentation

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2020-08-12
    相关资源
    最近更新 更多