PyQt4的udp广播似乎不起作用

时间:2011-12-12 14:37:53

标签: python udp pyqt4 broadcast

我在PyQt4中编写的应用程序似乎没有获得任何数据。 readyRead事件甚至没有被触发。 使用这些应用程序如下:

python server.py -s -p 50000 #(server on port 50000)
python server.py -c -p 50000 #(client sending data to port 50000)

//

import sys
import time

from PyQt4 import QtNetwork, QtCore
from optparse import OptionParser

class Server(object):

    def __init__(self, port):

        self.port = port

        try:
            self.socket = QtNetwork.QUdpSocket()
            self.socket.bind(QtNetwork.QHostAddress.Broadcast, int(self.port), QtNetwork.QUdpSocket.ShareAddress)

            self.socket.readyRead.connect(self.receiver)

        except QtNetwork.QUdpSocket.NetworkError:
            print "EXCEPTION DURING INITIALIZING SERVER'S SOCKET"
            sys.exit(1)

    def receiver(self):
        print "DEBUG: RECEIVE"
        while(self.socket.hasPendingDatagrams()):
            try:
                size = self.socket.pendingDatagramSize()
                msg, host, port = self.socket.readDatagram(size)
            except:
                print "EXCEPTION DURING RECEIVEING AND READING DATAGRAM"
            else:
                print "HOST %s:%s MSG: %s" % (str(host), str(port), str(msg))

    def __del__(self):
        print "DESTRUCTOR"
        self.socket.close()

class Client(object):

    def __init__(self, port):

        self.port = port

        try:
            self.socket = QtNetwork.QUdpSocket()
        except:
            print "EXCEPTION DURING INITIALIZING CLIENT'S SOCKET"

        self.main_loop()

    def main_loop(self):
        for i in range(20):
            self.debug_msg()
            time.sleep(0.5)
        print "EXITING"
        self.socket.close()


    def debug_msg(self):
        msg = "DEBUG"
        self.socket.writeDatagram(msg, QtNetwork.QHostAddress.Broadcast, int(self.port))


if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("-p", "", action="store", type="string", dest="port")
    parser.add_option("-c", "", action="store_true", dest="client")
    parser.add_option("-s", "", action="store_true", dest="server")

    options, args = parser.parse_args()

    if not (options.server or options.client):
        print "Client/Server not specified. Could not continue..."
        sys.exit(1)

    elif not options.port:
        print "Server's port not specified. Could not continue..."
        sys.exit(1)

    else:

        if options.server:
            serv = Server(options.port)

            App = QtCore.QCoreApplication(sys.argv)
            sys.exit(App.exec_())
        else:
            client = Client(options.port)

2 个答案:

答案 0 :(得分:1)

在您的客户端,您没有启动Qt的事件循环。您应该分配一个应用程序对象,并在其上调用exec_并通过计时器处理debug_msg调用,或者您应该使用QCoreApplication.processEvents()来抽取事件循环。

另一种选择是使用flush():

http://doc.qt.nokia.com/latest/qabstractsocket.html#flush

  

bool QAbstractSocket::flush ()

     

此函数尽可能从内部写入写入   缓冲到底层网络套接字,没有阻塞。如有任何数据   写了,这个函数返回true;否则返回false。

     

如果需要QAbstractSocket开始发送,请调用此函数   立即缓冲数据。成功写入的字节数   取决于操作系统。在大多数情况下,您不需要   调用此函数,因为QAbstractSocket将开始发送数据   一旦控制返回到事件循环,自动。离席期间   一个事件循环,请调用waitForBytesWritten()。

答案 1 :(得分:0)

QtNetwork.QUdpSocket.NetworkError不是异常类型,只是一个常量。而且,为什么要将套接字绑定到QHostAddress.Broadcast。您需要QHostAddress.Any吗?