pyqt5 基于UDP的简单聊天室

UDP通信过程:

创建QUdpSocket,之后将socket绑定到对应的端口号,在接受文本时,socket函数会触发readyRead信号,在对应的槽函数中编写处理数据处理的过程,读取数据使用readDatagram函数。

# def readDatagram(self, p_int):  # real signature unknown; restored from __doc__
#     """ readDatagram(self, int) -> Tuple[bytes, QHostAddress, int] """
#     pass

而在相应的界面中通过点击按钮或者使用键盘快捷键触发writeDatagram函数,向socket函数中写入数据,之后将数据发送到所指定的IP和端口的应用程序。

# def writeDatagram(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads
#     """
#     writeDatagram(self, bytes, Union[QHostAddress, QHostAddress.SpecialAddress], int) -> int
#     writeDatagram(self, Union[QByteArray, bytes, bytearray], Union[QHostAddress, QHostAddress.SpecialAddress], int) -> int
#     writeDatagram(self, QNetworkDatagram) -> int
#     """
#     return 0
源代码如下:
import sys
from server import Ui_Form
from PyQt5.QtNetwork import QUdpSocket, QHostAddress
from PyQt5.QtCore import QDataStream, QIODevice, QByteArray
from PyQt5.QtWidgets import QWidget, QApplication

class UdpCommunication(Ui_Form, QWidget):
    def __init__(self):
        super(UdpCommunication, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.udpSocket = QUdpSocket()                              #创建socket

        self.udpSocket.bind(8888)                                  #绑定端口并监听
        self.ui.pushButton_send.clicked.connect(self.handleSend)   
        self.udpSocket.readyRead.connect(self.handleRecv)

    # def writeDatagram(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads
    #     """
    #     writeDatagram(self, bytes, Union[QHostAddress, QHostAddress.SpecialAddress], int) -> int
    #     writeDatagram(self, Union[QByteArray, bytes, bytearray], Union[QHostAddress, QHostAddress.SpecialAddress], int) -> int
    #     writeDatagram(self, QNetworkDatagram) -> int
    #     """
    #     return 0

    def handleSend(self):
        text = self.ui.textEdit.toPlainText()
        ip = self.ui.lineEdit_IP.text()
        port = int(self.ui.lineEdit_PORT.text())

        # message = QByteArray()
        # data = QDataStream(message, QIODevice.WriteOnly)
        # data.writeQString(text)
        message = bytes(text, encoding="utf-8")
        self.udpSocket.writeDatagram(message, QHostAddress(ip), port)

    # def readDatagram(self, p_int):  # real signature unknown; restored from __doc__
    #     """ readDatagram(self, int) -> Tuple[bytes, QHostAddress, int] """
    #     pass

    def handleRecv(self):
        buf = bytes()
        buf, ip, port = self.udpSocket.readDatagram(1024)
        message = buf.decode()
        self.ui.textEdit.setText(message)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = UdpCommunication()
    win.show()
    sys.exit(app.exec_())
在一台电脑上只要使用不同的端口号,便可以模仿在本地通过网络进行通信

猜你喜欢

转载自blog.csdn.net/wh_585/article/details/79707715