pyqt5 基於UDP的簡單聊天室
阿新 • • 發佈:2019-02-07
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_())