python udp报文接收
# coding=utf-8 #!/usr/bin/env python from PyQt5.QtCore import QPoint, QRect, QSize, Qt from PyQt5.QtWidgets import (QApplication, QLayout, QPushButton, QSizePolicy,QVBoxLayout, QWidget) from PyQt5.Qt import QTextEdit, QLineEdit from PyQt5.QtNetwork import * import struct import datetime def num2Ip(num): ip = "%d.%d.%d.%d" % ((num>>24)&0xff,(num>>16)&0xff,(num>>8)&0xff,num&0xff) return ip class Window(QWidget): def __init__(self): super(Window, self).__init__() self.fp = open("test.log","w") flowLayout = QVBoxLayout() self.ip = QLineEdit() self.textEdit = QTextEdit() self.textEdit.setReadOnly(True) self.btn = QPushButton("清空日志") self.btn.clicked.connect(self.clearData) flowLayout.addWidget(self.btn) flowLayout.addWidget(self.textEdit) self.setLayout(flowLayout) self.setWindowTitle("日志监控") self.port = 7700 self.udpSocket = QUdpSocket(self) self.udpSocket.readyRead.connect(self.dataReceive) result = self.udpSocket.bind(self.port) def clearData(self): self.textEdit.clear() def dataReceive(self): while self.udpSocket.hasPendingDatagrams(): msglist = self.udpSocket.readDatagram(self.port) msg = msglist[0] length = len(msg) if length == 23: chl_id,ip_num,slot_id,counter,receiveFrameMode,snr,offsetFreqStatus = struct.unpack('!BIHIBHI', msg[0:-5]) time=datetime.datetime.now() text = (time,chl_id,num2Ip(ip_num),slot_id,counter,receiveFrameMode,snr,offsetFreqStatus) self.textEdit.insertPlainText(str(text)) self.textEdit.insertPlainText("\r\n") self.fp.write(str(text) + "\r\n") if __name__ == '__main__': import sys app = QApplication(sys.argv) mainWin = Window() mainWin.show() sys.exit(app.exec_())
联系方式:heshengjun@tinywsn.com