0

试图将用 C++ 编写的服务器转换为 Python。服务器被写入异步/非阻塞。在 C++ 中有效的东西似乎不想在 Python 中为我工作

我正在使用 PyQT4。我读过 Python 你必须创建事件循环或类似的东西任何想法都非常感谢

我应该提到似乎不起作用的是Class Server中的incomingConnection函数永远不会被调用。

*干杯

import sys
from PyQt4.QtCore import *
from PyQt4.QtNetwork import *


class Client(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self)
        QThreadPool.globalInstance().setMaxThreadCount(15)

    def SetSocket(self, Descriptor):
        self.socket = QTcpSocket(self)
        self.connect(self.socket, SIGNAL("connected()"), SLOT(self.connected()))
        self.connect(self.socket, SIGNAL("disconnected()"), SLOT(self.disconnected()))
        self.connect(self.socket, SIGNAL("readyRead()"), SLOT(self.readyRead()))

        self.socket.setSocketDescriptor(Descriptor)
        print "Client Connected from IP %s" % self.socket.peerAddress().toString()

    def connected(self):
        print "Client Connected Event"

    def disconnected(self):
        print "Client Disconnected"

    def readyRead(self):
        msg = self.socket.readAll()
        print msg


class Server(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self)

    def incomingConnection(self, handle):
        print "incoming"
        self.client = Client(self)
        self.client.SetSocket(handle)

    def StartServer(self):
        self.server = QTcpServer()
        if self.server.listen(QHostAddress("0.0.0.0"), 8888):
            print "Server is awake"    
        else:
            print "Server couldn't wake up"


def main():
    app = QCoreApplication(sys.argv)
    Server().StartServer()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
4

1 回答 1

1

incomingConnection未调用,因为调用QTcpServer了函数的基本实现。作为incomingConnection一个虚拟功能,您只需将您的分配给 QTcpServer 的incomingConnection 属性,如下所示:

class Server(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self)

    def incomingConnection(self, handle):
        print "incoming"
        self.client = Client(self)
        self.client.SetSocket(handle)

    def StartServer(self):
        self.server = QTcpServer()
        self.server.incomingConnection = self.incomingConnection
        if self.server.listen(QHostAddress("0.0.0.0"), 8888):
            print "Server is awake"    
        else:
            print "Server couldn't wake up"

你可以查看 PySide 的文档,因为它比 PyQt 的更 Pythonic,目前仅在此处托管: http ://srinikom.github.com/pyside-docs/

于 2012-11-04T07:53:53.497 回答