def __init__(self, ip_addr, temp_gcode_file, log_enabled=False): super().__init__() self._ip = QHostAddress(ip_addr) self._localTempGcode = temp_gcode_file self._port = 3000 self.BUFSIZE = 1280 self._file_encode = 'utf-8' self._abort = False self._filename = None self._log_enabled = log_enabled self._connected = False self._socket = QUdpSocket(self) self._last_reply = None self._isPrinting = False self._isIdle = False self._print_now = 0 self._print_total = 0 self._busy = False self._printing_filename = "" self._firmware_ver = "" self._printing_time = 0 self._update_fail_cnt = 0 self._last_times = [] self._status = {} self._mutex = Lock() self._config = {'e_mm_per_step': '0.0', 's_machine_type': '0', 's_x_max': '0.0', 's_y_max': '0.0', 's_z_max': '0.0', 'x_mm_per_step': '0.0', 'y_mm_per_step': '0.0', 'z_mm_per_step': '0.0'} self.__log("d", "LocalPort: {}", self._socket.localPort())
def createConnection(self, localIP, localPort): localaddr = QHostAddress() localaddr.setAddress(localIP) self.setLocalIp(localIP) self.setLocalPort(localPort) isOK = self.udpSocket.bind(localaddr, localPort) return isOK
def __init__(self, host=None, port=None, type=None, parent=None): super(UDPClient, self).__init__(parent) mcast_addr = host mcast_port = port type = type self.statusLabel = QLabel("Listening for broadcasted messages") quitButton = QPushButton("&Quit") self.udpSocket = QUdpSocket(self) dstAddress = QHostAddress() dstAddress.setAddress(mcast_addr) self.udpSocket.bind(dstAddress, mcast_port) self.udpSocket.readyRead.connect(self.processPendingDatagrams) quitButton.clicked.connect(self.close) buttonLayout = QHBoxLayout() buttonLayout.addStretch(1) buttonLayout.addWidget(quitButton) buttonLayout.addStretch(1) mainLayout = QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout) self.setWindowTitle("Broadcast Receiver")
def sessionOpened(self): if self.networkSession is not None: config = self.networkSession.configuration() if config.type() == QNetworkConfiguration.UserChoice: id = self.networkSession.sessionProperty('UserChoiceConfiguration') else: id = config.identifier() settings = QSettings(QSettings.UserScope, 'QtProject') settings.beginGroup('QtNetwork') settings.setValue('DefaultNetworkConfiguration', id) settings.endGroup(); self.tcpServer = QTcpServer(self) if not self.tcpServer.listen(): QMessageBox.critical(self, "Fortune Server", "Unable to start the server: %s." % self.tcpServer.errorString()) self.close() return for ipAddress in QNetworkInterface.allAddresses(): if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0: break else: ipAddress = QHostAddress(QHostAddress.LocalHost) ipAddress = ipAddress.toString() self.statusLabel.setText("The server is running on\n\nIP: %s\nport %d\n\n" "Run the Fortune Client example now." % (ipAddress, self.tcpServer.serverPort()))
def ipAddressFieldUpdated(self): hostAddress = QHostAddress() if hostAddress.setAddress(self.ipAddressField.text()): self.ipAddress = self.ipAddressField.text() else: self.ipAddress = None
def __init__(self, sock_type='TCP Client', ip='127.0.0.1', port=2007): '''打开网络设备,建立连接 ## sock_type: - 'TCP Client' - 'TCP Server' - 'UDP' ''' self.sock_type = sock_type # self.ip = ip self.port = port if sock_type == 'TCP Client': tcp_client = QTcpSocket() tcp_client.connectToHost(ip, port) self.sock = tcp_client elif sock_type == 'TCP Server': tcp_server = QTcpServer() tcp_server.listen(QHostAddress(ip), port) self.sock = tcp_server elif sock_type == 'UDP': udp = QUdpSocket() udp.bind(QHostAddress(ip), port) self.sock = udp else: print('Unkonw sock_type=%r' % sock_type)
def __init__(self): super().__init__() self.config = Config("config.ini") # INIT Controls self.wheels = Wheels(self.config.steeringMid, self.config.steeringLeft, self.config.steeringRight) self.accelerator = Accelerator(self.config, self) self.__initUI() self.statusBar().showMessage("Board not connected") # Init uds listener self._log("Init udp at {}:{}".format( get_ip(), self.config.getOption('udp_port'))) self.udpSocket = QUdpSocket() self.udpSocket.setLocalAddress(QHostAddress(get_ip())) self.udpSocket.bind(self.config.getOption('udp_port')) self.udpSocket.readyRead.connect(self.udpHandler) # Init tcp server self.tcpServer = QTcpServer(self) self._log("Starting TCP at {}:{} ".format( get_ip(), str(self.config.getOption('tcp_port')))) self.tcpServer.listen(QHostAddress(get_ip()), self.config.getOption('tcp_port')) self.tcpServer.newConnection.connect(self.establishBoardConnection) self.show()
def handleRecv(self): ip = QHostAddress() buf = bytes() buf, ip, port = self.udpSocket.readDatagram(1024) ip = ip.toString() message = buf.decode() self.ui.textEdit.setText('{Ip},{Port}:{Message}'.format(Ip=ip, Port=port, Message=message))
def __init__(self): super().__init__() self.isUp = False self.port = 8888 self.serverIP = QHostAddress('127.0.0.1') self.tcpClientList = [] self.initUi()
def pressLoginBtn(self): '''登录按钮槽函数,将账户 密码 状态(在这里设置为0:用户,1:管理员) 发送到服务器''' # 判断是否获取信息成功 if self.count_lineEdit.text() == "" or self.passwd_lineEdit.text( ) == "": QMessageBox.warning(self, ("Warning"), ("未输入帐号或密码,请重新输入"), QMessageBox.Yes) else: # 获取帐号密码帐号 self.data.set_count(self.count_lineEdit.text()) self.data.set_passwd(self.passwd_lineEdit.text()) #用户登录 if self.userRadioButton.isChecked(): self.data.set_status(0) self.udp_client_socket.writeDatagram( self.data.login_struct_pack(), QHostAddress(LOGIN_SERVER_IP), LOGIN_SERVER_PORT) print("login_client send message ok") # 管理员登录 elif self.managerRadioButton.isChecked(): self.data.set_status(1) self.udp_client_socket.writeDatagram( self.data.login_struct_pack(), QHostAddress(LOGIN_SERVER_IP), LOGIN_SERVER_PORT) print("login_client send message ok")
def run(self): localHostName = QHostInfo.localHostName() hostinfo = QHostInfo.fromName(localHostName) listaddress = hostinfo.addresses() for address in listaddress: if QHostAddress( address).protocol() == QAbstractSocket.IPv4Protocol: address = QHostAddress(address).toString() print(address) host_info = "" confList = QNetworkConfigurationManager().allConfigurations() print("confList = ", confList.__len__()) for conf in confList: if str(conf.bearerTypeName()) == "Ethernet": host_info += "\n" host_info += "name : " + QNetworkConfiguration( conf).name() + "\n" host_info += str(QNetworkConfiguration(conf).isValid()) + "\n" host_info += "bearerType: " + QNetworkConfiguration( conf).bearerTypeName() + "\n" list = QNetworkInterface.allInterfaces() for interface in list: host_info += "\n" host_info += "=============================\n" host_info += "name: " + interface.name() + "\n" host_info += QNetworkInterface(interface).hardwareAddress() + "\n" host_info += str(QNetworkInterface(interface).isValid()) + "\n" host_info += "---------\n" if QNetworkInterface(interface).flags() & QNetworkInterface.IsUp: host_info += "Interface: is up\n" if QNetworkInterface( interface).flags() & QNetworkInterface.IsLoopBack: host_info += "Interface: is loop back\n" # 迴環地址 if QNetworkInterface( interface).flags() & QNetworkInterface.IsRunning: host_info += "Interface: is running \n" # 網絡已經啓動運行 if interface.flags() & QNetworkInterface.CanMulticast: host_info += "Interface: CanMulticast\n" # 多播 if interface.flags() & QNetworkInterface.CanBroadcast: host_info += "Interface: CanBroadcast\n" host_info += "---------\n" entryList = QNetworkInterface(interface).addressEntries() for entry in entryList: address = entry.ip() if QHostAddress(address).protocol( ) == QAbstractSocket.IPv4Protocol: # and \ # str(address.toString()) != "127.0.0.1": host_info += "IP Address: " + QNetworkAddressEntry( entry).ip().toString() + "\n" host_info += "Netmask: " + QNetworkAddressEntry( entry).netmask().toString() + "\n" host_info += "Broadcast: " + QNetworkAddressEntry( entry).broadcast().toString() + "\n" host_info += "=============================\n" self.sig.emit(host_info)
def udp_slave(self, port1, port2): self.socket1 = QUdpSocket() self.socket2 = QUdpSocket() self.socket1.bind(QHostAddress(config.host), port1) self.socket2.bind(QHostAddress(config.host), port2) self.socket1.readyRead.connect(self.on_udp_receive1) self.socket2.readyRead.connect(self.on_udp_receive2)
def getIPAddress(): for ipAddress in QNetworkInterface.allAddresses(): if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address( ) != 0: break else: ipAddress = QHostAddress(QHostAddress.LocalHost) return ipAddress.toString()
def __init__(self, input_ipAdress, input_port): self.host_ip = QHostAddress(input_ipAdress) self.port = input_port self.udp_socket = QUdpSocket() # udp_socket.bind(QHostAddress('192.168.43.126'),port) print(self.udp_socket.bind(QHostAddress('localhost'), self.port))
def __init__(self, parent=None): super(BlockingClient, self).__init__(parent) self.thread = FortuneThread() self.currentFortune = "" hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") for ipAddress in QNetworkInterface.allAddresses(): if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address( ) != 0: break else: ipAddress = QHostAddress(QHostAddress.LocalHost) ipAddress = ipAddress.toString() self.hostLineEdit = QLineEdit(ipAddress) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostLineEdit) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel( "This example requires that you run the Fortune Server example as well." ) self.statusLabel.setWordWrap(True) self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.thread.newFortune.connect(self.showFortune) self.thread.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostLineEdit, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Blocking Fortune Client") self.portLineEdit.setFocus()
def __init__(self, parent=None): super(BlockingClient, self).__init__(parent) self.thread = FortuneThread() self.currentFortune = '' hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") for ipAddress in QNetworkInterface.allAddresses(): if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0: break else: ipAddress = QHostAddress(QHostAddress.LocalHost) ipAddress = ipAddress.toString() self.hostLineEdit = QLineEdit(ipAddress) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostLineEdit) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel( "This example requires that you run the Fortune Server example as well.") self.statusLabel.setWordWrap(True) self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.thread.newFortune.connect(self.showFortune) self.thread.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostLineEdit, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Blocking Fortune Client") self.portLineEdit.setFocus()
def isValidAddress(address): """ Public function to check, if the given address is valid. @param address IPv4 or IPv6 address string @type str @return flag indicating validity @rtype bool """ h = QHostAddress(address) return not h.isNull()
def __init__(self, udpc, logger: Logger, name="Ana", parent=None): super().__init__(logger=logger, parent=parent) self.udpc = udpc self.addr = QHostAddress(udpc.addr) self.port = udpc.port self.transport = Transport() self.socket = QUdpSocket(self) self.socket.bind(QHostAddress(udpc.local_addr), udpc.local_port) self.rid = udpc.rid self.add_rid(udpc.rid) self.name = name
def isValidIPv6Address(address): """ Public function to check, if the given address is a valid IPv6 address. @param address IPv6 address string @type str @return flag indicating validity @rtype bool """ h = QHostAddress(address) return not h.isNull() and h.protocol() == QAbstractSocket.IPv6Protocol
def loadSettings(self, config): self.serverAddress = QHostAddress( config.get("communication", "serverGamepadAddress")) self.serverPort = int(config.get("communication", "serverGamepadPort")) self.clientAddress = QHostAddress( config.get("communication", "clientGamepadAddress")) self.clientPort = int(config.get("communication", "clientGamepadPort")) self.sensorBroadcastAddress = QHostAddress( config.get("communication", "serverRoverAddress")) self.sensorBroadcastPort = int( config.get("communication", "serverRoverPort")) self.reconnect = True
def unblock(self, addressString: str): if not blockedAddresses: self.socket.write(b'There is no blocked address to unblock.\n') return address = QHostAddress(addressString) if address == QHostAddress(): self.socket.write(b"'" + addressString.encode() + b"' is no valid host address.\n") return if blockedAddresses.pop(address, None) == None: self.socket.write(b"The address '" + addressString.encode() + b"' is not blocked.\n") else: self.socket.write(b"The address '" + addressString.encode() + b"' has been unblocked.\n")
def __init__(self): super(Main, self).__init__() # 初始化,super集成父类的属性 self.ui = PreviewApp.Ui_MainWindow() # 实例化 self.ui.setupUi(self) self.setWindowIcon(QIcon('db/logo.jpg')) self.db = QSqlDatabase.addDatabase('QSQLITE') self.db.setDatabaseName('db/App.db') self.db.open() self.tableView = self.ui.tableView # 获取TableView对象 self.tableView1 = self.ui.tableView1 self.model = QSqlTableModel(self) # 设置数据库模型 self.model.setTable("Preview") # 选择db的其中一个表 self.tableView.setModel(self.model) # 设置TableView的模型 self.tableView.setEditTriggers(QTableView.NoEditTriggers) # 设置表1内容不可编辑 self.model.select() # model1为页面2对象 self.model1 = QSqlTableModel(self) self.model1.setTable("Container") self.tableView1.setModel(self.model1) self.model1.select() self.ui.btn1.clicked.connect(self.addRow) self.ui.btn2.clicked.connect(self.delRow) self.ui.btn3.clicked.connect(self.CPU) self.ui.btn4.clicked.connect(self.Memory) self.ui.btn5.clicked.connect(self.CPU_temp) self.ip_list = [] self.tcpserver = TcpServer(self) self.tcpserver.listen(QHostAddress("0,0,0,0,"), Port) # 绑定监听端口 self.tcpserver.signRecv.connect(self.Recv) # self.tcpserver.signGetAddress.connect(self.updateCombox) self.updateCombox()
def show_item(self, mac, port): self.monitor.setText(mac) self.monitor.show() self.label.show() self.socket_.bind(QHostAddress(self.ip), port) self.socket_.readyRead.connect(self.show_video) self.detail_device = Device(monitor=self)
def __init__(self, ip, port): super(MyTcpSocket, self).__init__() self.ip = ip self.port = port self.connectToHost(QHostAddress(self.ip), self.port) self.connected.connect(lambda: print("连接成功")) self.disconnected.connect(self.dealDisconnected)
def send(self, data, dstIp, dstPort): """ udp-发送 :param data: str or bytearray :param dstIp: :param dstPort: :return: """ dstAddress = QHostAddress() dstAddress.setAddress(dstIp) if isinstance(data, str): self.udpSocket.writeDatagram(data, dstAddress, dstPort) elif isinstance(data, bytearray) or isinstance(data, bytes): self.udpSocket.writeDatagram(QByteArray(data), dstAddress, dstPort) else: print('unexpected input type!')
def _is_url_naive(urlstr): """Naive check if given URL is really a URL. Args: urlstr: The URL to check for, as string. Return: True if the URL really is a URL, False otherwise. """ url = qurl_from_user_input(urlstr) assert url.isValid() if not utils.raises(ValueError, ipaddress.ip_address, urlstr): # Valid IPv4/IPv6 address return True # Qt treats things like "23.42" or "1337" or "0xDEAD" as valid URLs # which we don't want to. Note we already filtered *real* valid IPs # above. if not QHostAddress(urlstr).isNull(): return False if '.' in url.host(): return True else: return False
def __init__(self, inp_host, inp_port): super().__init__() self.lock = QReadWriteLock() self.recordSignal = RecordSignal() self.recordSignal.sendSignal.connect(self.my_record) self.tcpServer = TcpServer(self.recordSignal, self.lock) if not self.tcpServer.listen(QHostAddress(inp_host), inp_port): QMessageBox.critical( self, '交易服务器', '服务器启动失败:{0}'.format(self.tcpServer.errorString())) rec_text = my_cur_time() + ' 服务器启动失败!' try: self.lock.lockForWrite() self.recordSignal.sendSignal.emit(rec_text) finally: self.lock.unlock() self.close() return else: self._initUI() rec_text = my_cur_time() + ' 开启交易服务器!' try: self.lock.lockForWrite() self.recordSignal.sendSignal.emit(rec_text) finally: self.lock.unlock()
def _readyRead(self): while self.hasPendingDatagrams(): data, host, port = self.readDatagram(self.pendingDatagramSize()) ipv4_address_string = QHostAddress(host.toIPv4Address()).toString( ) # host.toString() is expressed as IPv6 otherwise e.g. ::ffff:91.64.56.230 if data is not None: self.handle_data((ipv4_address_string, int(port)), data)
def _is_url_dns(urlstr): """Check if a URL is really a URL via DNS. Args: url: The URL to check for as a string. Return: True if the URL really is a URL, False otherwise. """ url = qurl_from_user_input(urlstr) assert url.isValid() if (utils.raises(ValueError, ipaddress.ip_address, urlstr) and not QHostAddress(urlstr).isNull()): log.url.debug("Bogus IP URL -> False") # Qt treats things like "23.42" or "1337" or "0xDEAD" as valid URLs # which we don't want to. return False host = url.host() if not host: log.url.debug("URL has no host -> False") return False log.url.debug("Doing DNS request for {}".format(host)) info = QHostInfo.fromName(host) return not info.error()
def __init__(self): """ Constructor of the BackgroundService class. """ self.processes = {} self.connections = {} self.isWorking = None self.runningJob = [None, None, None, None] self.__queue = [] self.services = {} super(BackgroundService, self).__init__() networkInterface = Preferences.getDebugger("NetworkInterface") if networkInterface == "all" or '.' in networkInterface: self.hostAddress = '127.0.0.1' else: self.hostAddress = '::1' self.listen(QHostAddress(self.hostAddress)) self.newConnection.connect(self.on_newConnection) port = self.serverPort() ## Note: Need the port if started external in debugger: print('BackgroundService listening on: %i' % port) for pyName in ['Python', 'Python3']: interpreter = Preferences.getDebugger(pyName + "Interpreter") process = self.__startExternalClient(interpreter, port) if process: if pyName == 'Python': pyName = 'Python2' self.processes[pyName] = process, interpreter
def __init__(self, main_window, on_connection, log, stop_signal): super().__init__() self.log = log.getChild('TCP') self.log.info('Initializing') self.main_window = main_window self.on_connection = on_connection self.stop_signal = stop_signal self.host, self.port = CONFIG.listen_address self.host = QHostAddress(self.host) self.benchmark = CONFIG['benchmark'] self.threads = [] self.connections = 0
def myIpAddress(self): """Get host IP address. Return the server IP address of the current machine, as a string in the dot-separated integer format. """ return QHostAddress(QHostAddress.LocalHost).toString()
def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.server = FortuneServer() statusLabel = QLabel() statusLabel.setWordWrap(True) quitButton = QPushButton("Quit") quitButton.setAutoDefault(False) if not self.server.listen(): QMessageBox.critical(self, "Threaded Fortune Server", "Unable to start the server: %s." % self.server.errorString()) self.close() return for ipAddress in QNetworkInterface.allAddresses(): if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0: break else: ipAddress = QHostAddress(QHostAddress.LocalHost) ipAddress = ipAddress.toString() statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n" "Run the Fortune Client example now." % (ipAddress, self.server.serverPort())) quitButton.clicked.connect(self.close) buttonLayout = QHBoxLayout() buttonLayout.addStretch(1) buttonLayout.addWidget(quitButton) buttonLayout.addStretch(1) mainLayout = QVBoxLayout() mainLayout.addWidget(statusLabel) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout) self.setWindowTitle("Threaded Fortune Server")
def __init__(self, dialog, parent=None): dialog.setObjectName("udp-test") dialog.resize(480, 400) super(UiDialog, self).__init__(parent) self.pushButton_2 = QtWidgets.QPushButton(dialog) self.pushButton = QtWidgets.QPushButton(dialog) self.textEdit = QtWidgets.QTextEdit(dialog) self.textEdit_port = QtWidgets.QTextEdit(dialog) self.textEdit_url = QtWidgets.QTextEdit(dialog) self.textBrowser = QtWidgets.QTextBrowser(dialog) self.udpSocket_sed = QUdpSocket() self.udpSocket_rev = QUdpSocket() # self.udpSocket_rev.bind(self.port_udp) self.udpSocket_rev.readyRead.connect(self.upd_rev) self.url = QHostAddress() self.url.setAddress("127.0.0.1") self.ret_ui(dialog) QtCore.QMetaObject.connectSlotsByName(dialog)
class UiDialog(QDialog): port_udp = 1345 def __init__(self, dialog, parent=None): dialog.setObjectName("udp-test") dialog.resize(480, 400) super(UiDialog, self).__init__(parent) self.pushButton_2 = QtWidgets.QPushButton(dialog) self.pushButton = QtWidgets.QPushButton(dialog) self.textEdit = QtWidgets.QTextEdit(dialog) self.textEdit_port = QtWidgets.QTextEdit(dialog) self.textEdit_url = QtWidgets.QTextEdit(dialog) self.textBrowser = QtWidgets.QTextBrowser(dialog) self.udpSocket_sed = QUdpSocket() self.udpSocket_rev = QUdpSocket() # self.udpSocket_rev.bind(self.port_udp) self.udpSocket_rev.readyRead.connect(self.upd_rev) self.url = QHostAddress() self.url.setAddress("127.0.0.1") self.ret_ui(dialog) QtCore.QMetaObject.connectSlotsByName(dialog) def setup_ui(self): self.textBrowser.setGeometry(QtCore.QRect(40, 50, 301, 221)) self.textBrowser.setObjectName("textBrowser") self.textEdit.setGeometry(QtCore.QRect(40, 290, 301, 74)) self.textEdit.setObjectName("textEdit") self.textEdit_port.setGeometry(QtCore.QRect(360, 150, 120, 20)) self.textEdit_port.setObjectName("textEdit_port") self.textEdit_url.setGeometry(QtCore.QRect(360, 200, 120, 20)) self.textEdit_url.setObjectName("textEdit_url") self.pushButton.setGeometry(QtCore.QRect(360, 50, 120, 32)) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.upd_sed) self.pushButton_2.setGeometry(QtCore.QRect(360, 100, 120, 32)) self.pushButton_2.setObjectName("pushButton_2") self.pushButton_2.clicked.connect(self.port_ui) def ret_ui(self, dialog): _translate = QtCore.QCoreApplication.translate dialog.setWindowTitle(_translate("udp-test", "udp网络测试工具")) self.pushButton.setText(_translate("udp-test", "发送")) self.pushButton_2.setText(_translate("udp-test", "确认端口及地址")) self.textEdit_port.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'.SF NS Text\'; font-size:13pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1345</p></body></html>")) self.textEdit_url.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'.SF NS Text\'; font-size:13pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">127.0.0.1</p></body></html>")) def port_ui(self): self.port_udp = int(self.textEdit_port.toPlainText()) self.url.setAddress(str(self.textEdit_url.toPlainText())) self.udpSocket_rev.bind(self.port_udp) def upd_rev(self): while self.udpSocket_rev.hasPendingDatagrams(): datagram, host, port = self.udpSocket_rev.readDatagram(self.udpSocket_rev.pendingDatagramSize()) try: # Python v3. datagram = str(datagram, encoding='utf-8') except TypeError: # Python v2. pass self.textBrowser.insertPlainText("发自 {}:{} 到 localhost:{}:\n".format(host.toIPv6Address()[-4:], port, str(self.port_udp)) + datagram + '\n') def upd_sed(self): datagram = str(self.textEdit.toPlainText()) self.udpSocket_sed.writeDatagram(datagram.encode("utf-8"), self.url, self.port_udp)