pythonpyqtpyqt5qtnetworkqudpsocket

QUdpSocket doesn't have writeDatagram() function in PyQt5?


Why in PyQt5 QUdpSocket doesn't have writeDatagram() but just write() and writeData()?

Then how can I send the data to the certain IP address and port?


Solution

  • QUdpSocket does have the writeDatagram() method.

    from PyQt5 import QtCore, QtNetwork
    
    
    class Sender(QtCore.QObject):
        def __init__(self, parent=None):
            super(Sender, self).__init__(parent)
            self._socket = QtNetwork.QUdpSocket(self)
    
        @QtCore.pyqtSlot()
        def send_message(self):
            message = QtCore.QDateTime.currentDateTime().toString()
            datagram = message.encode()
            print("send message:", message)
            self._socket.writeDatagram(
                datagram, QtNetwork.QHostAddress("127.0.0.1"), 45454
            )
    
    
    class Receiver(QtCore.QObject):
        def __init__(self, parent=None):
            super(Receiver, self).__init__(parent)
            self._socket = QtNetwork.QUdpSocket(self)
            self._socket.bind(QtNetwork.QHostAddress("127.0.0.1"), 45454)
            self._socket.readyRead.connect(self.on_readyRead)
    
        @QtCore.pyqtSlot()
        def on_readyRead(self):
            while self._socket.hasPendingDatagrams():
                datagram, host, port = self._socket.readDatagram(
                    self._socket.pendingDatagramSize()
                )
                print("message from:", host.toString())
                print("message port:", port)
                print("message:", datagram.decode())
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtCore.QCoreApplication(sys.argv)
        receiver = Receiver()
        sender = Sender()
        timer = QtCore.QTimer(interval=1000, timeout=sender.send_message)
        timer.start()
        sys.exit(app.exec_())