QUdpSocket 在 PyQt5 中没有 writeDatagram() 函数?

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

为什么在 PyQt5 中 QUdpSocket 没有 writeDatagram() 而只有 write() 和 writeData()?

那我怎样才能把数据发送到指定的IP地址和端口呢?

QUdpSocket 确实有 writeDatagram() 方法。

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