def comboboxInit(self): # 工具选择框combox self.widgetui.comboBoxStyle.insertItem(0, "UDP") self.widgetui.comboBoxStyle.insertItem(1, "TCP Client") self.widgetui.comboBoxStyle.insertItem(2, "TCP Server") self.widgetui.comboBoxStyle.insertItem(3, "COM Tool") self.connectModeList = list() self.connectModeList.append('UDP') self.connectModeList.append('TCP Client') self.connectModeList.append('TCP Server') self.connectModeList.append('COM Tool') self.widgetui.comboBoxStyle.activated.connect(self.comboxClicked) # 波特率combox self.widgetui.comboBoxBaud.insertItems(0, baudList) self.widgetui.comboBoxBaud.setCurrentText("9600") self.widgetui.comboBoxBaud.hide() self.widgetui.comboComNum.hide() self.widgetui.comboBoxClientList.hide() # tcp的server专用的组合框 # 本地IP combobox self.myhostInfo = QHostInfo.fromName(QHostInfo.localHostName()) hostIpList = ICommunicateTCPIP.getLocalIpList() if '127.0.0.1' not in hostIpList: hostIpList.append('127.0.0.1') oldHostIp = str(self.myconfig.getValue("hostIp")) tempHostIp = str() for ip in hostIpList: self.widgetui.comboBoxLocal.addItem(ip) if oldHostIp == ip: tempHostIp = ip self.widgetui.comboBoxLocal.setCurrentText(tempHostIp) self.myaddress = self.widgetui.comboBoxLocal.currentText()
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 nickName(self): """ Public method to get the nick name. @return nick name (string) """ return "{0}@{1}@{2}".format(self.__username, QHostInfo.localHostName(), self.__servers[0].serverPort())
def run(self): # 获取IP socket = MyTcpsocket() socket.sign_recv.connect(self.sign_thread_recv) self.sign_thread_send.connect(socket.sign_send) hostname = QHostInfo.localHostName() info = QHostInfo.fromName(hostname) self.sign_thread_start.emit(info.addresses()[0].toString()) self.exec_()
def nickName(self): """ Public method to get the nick name. @return nick name (string) """ return "{0}@{1}@{2}".format( self.__username, QHostInfo.localHostName(), self.__servers[0].serverPort() )
def listen_host_info(self): if not self.listening: return None s = self._server hi = '%s port %d' % (s.serverAddress().toString(), s.serverPort()) from PyQt5.QtNetwork import QHostInfo host = QHostInfo.localHostName() if host: hi = '%s or %s' % (host, hi) return hi
def getLocalIpList(): """ 返回本地网卡的ip列表 :return: strlist """ myHostInfo = QHostInfo.fromName(QHostInfo.localHostName()) ipv4_addrs = list( filter( lambda myaddr: myaddr.protocol() == QAbstractSocket. IPv4Protocol, myHostInfo.addresses())) ipv4_straddrs = list(map(lambda myaddr: myaddr.toString(), ipv4_addrs)) return ipv4_straddrs
def sendMessage(self, messageType, serverAddress=""): """ 发送消息,serverAddress是服务器IP地址 """ localHostName = QHostInfo.localHostName() ipAddress = self.getIP() username = self.getUserName() data = { "messageType": messageType, "userName": username, "localHostName": localHostName } if messageType == Chat.Message: if self.messageTextEdit.toPlainText() == "": QMessageBox.warning(self, "警告", "发送内容不能为空", QMessageBox.Ok) return message = self.getMessage() data["ipAddress"] = ipAddress data["message"] = message elif messageType in (Chat.NewParticipant, Chat.ParticipantLeft): data["ipAddress"] = ipAddress elif messageType == Chat.FileName: row = self.userTableWidget.currentRow() clientAddress = self.userTableWidget.item(row, 2).text() data["ipAddress"] = ipAddress data["clientAddress"] = clientAddress data["sendFileName"] = self.fileName # 取得文件接收方的IP地址(clientAddress),然后将本机地址(服务器地址)、文件接收方(客户端地址)、发送的文件名 # 通过UDP协议广播出去。 elif messageType == Chat.Refuse: data["ipAddress"] = serverAddress # 消息类型是Chat.Refuse时,我们会把服务器端的地址带入 jdata = json.dumps(data) encodeData = bytes(jdata, encoding="utf-8") self.udpSocket.writeDatagram(encodeData, QHostAddress.Broadcast, self.port)
def onTimer(self): print("Timer") hostname = QHostInfo.localHostName() self.hostname_label.setText("ssh <username>@" + hostname + ".local.") if checkIfProcessRunning("sshd") == True: self.ssh_cb.setChecked(True) self.hostname_infolabel.setVisible(True) self.hostname_label.setVisible(True) self.vnc_cb.setEnabled(True) else: self.ssh_cb.setChecked(False) self.hostname_infolabel.setVisible(False) self.hostname_label.setVisible(False) self.vnc_infolabel.setVisible(False) self.vnc_cb.setEnabled(False) if checkIfProcessRunning("x11vnc") and checkIfProcessRunning("sshd") == True: self.vnc_cb.setChecked(True) self.vnc_infolabel.setVisible(True) else: self.vnc_cb.setChecked(False) self.vnc_infolabel.setVisible(False)
def sendMessage(self, messageType): """ 发送消息 """ localHostName = QHostInfo.localHostName() # 获得主机名 ipAddress = self.getIP() username = self.getUserName() data = { "messageType": messageType, "userName": username, "localHostName": localHostName } # 我们构建一个消息数据,这个数据的类型,我们定义为字典,里面放了消息类型、用户名、主机名。 if messageType == Chat.Message: if self.messageTextEdit.toPlainText() == "": QMessageBox.warning(self, "警告", "发送内容不能为空", QMessageBox.Ok) return message = self.getMessage() data["ipAddress"] = ipAddress data["message"] = message # 如果不是空消息,我们取得聊天框中的内容以及本地IP地址,并增加到消息数据当中。 elif messageType in (Chat.NewParticipant, Chat.ParticipantLeft): data["ipAddress"] = ipAddress # 要是我们发送的消息类型是:Chat.NewParticipant和Chat.ParticipantLeft(新人报到、用户离开),我们取得Ip地址后并增加到消息数据中 jdata = json.dumps(data) encodeData = bytes(jdata, encoding="utf-8") # 将消息data转成json格式,并通过bytes函数将其转成字节型的 self.udpSocket.writeDatagram(encodeData, QHostAddress.Broadcast, self.port)
def __init__(self, parent=None): super(Client, self).__init__(parent) self.networkSession = None self.blockSize = 0 self.currentFortune = '' self.title = "扫码收货PC辅助程序" hostLabel = QLabel('IP:') hostLabel.setFont(qtawesome.font('fa', 14)) portLabel = QLabel('端口:') portLabel.setFont(qtawesome.font('fa', 14)) taskCodeLabel = QLabel('任务码:') taskCodeLabel.setFont(qtawesome.font('fa', 14)) self.serverMsgLable = QLabel('来自服务端的消息:') self.serverMsgLable.setFont(qtawesome.font('fa', 14)) self.sendMsgLabel = QLabel('将要发送的消息:') self.sendMsgLabel.setFont(qtawesome.font('fa', 14)) self.hostCombo = QComboBox() self.hostCombo.setEditable(True) name = QHostInfo.localHostName() if name != '': self.hostCombo.addItem(name) domain = QHostInfo.localDomainName() if domain != '': self.hostCombo.addItem(name + '.' + domain) if name != 'localhost': self.hostCombo.addItem('10.286.88.124') ipAddressesList = QNetworkInterface.allAddresses() for ipAddress in ipAddressesList: if not ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) for ipAddress in ipAddressesList: if ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) self.portLineEdit.setPlaceholderText("请输入端口") self.taskLineEdit = QLineEdit() self.taskLineEdit.setPlaceholderText("请向组长询问后输入任务码") self.taskLineEdit.setValidator(QIntValidator(1, 9999, self)) self.serverLineEdit = QLineEdit() self.serverLineEdit.setPlaceholderText('服务器发送的消息会显示在这里') self.sendTextEdit = QTextEdit() self.sendTextEdit.setPlaceholderText('请输入先要发送给服务器的消息') hostLabel.setBuddy(self.hostCombo) portLabel.setBuddy(self.portLineEdit) taskCodeLabel.setBuddy(self.taskLineEdit) self.serverMsgLable.setBuddy(self.serverLineEdit) self.sendMsgLabel.setBuddy(self.sendTextEdit) self.statusLabel = QLabel("状态:尚未连接") self.statusLabel.setAutoFillBackground(True) self.statusLabel.setAlignment(Qt.AlignCenter) palette = QPalette() # 新建一个调色板 palette.setColor(QPalette.Window, Qt.red) # 设置颜色 self.statusLabel.setPalette(palette) self.statusLabel.setStyleSheet(''' color:#ffffff; font-size:18px; font-weight:bold; ''') self.getFortuneButton = QPushButton("启动连接") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("退出") self.stopButton = QPushButton("中止连接") self.stopButton.setDefault(True) self.stopButton.setEnabled(False) buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.stopButton, QDialogButtonBox.AcceptRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.sendMsgbutton = QPushButton('发送消息') self.webSocket = QWebSocket() self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.taskLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.CreateNewConn) self.stopButton.clicked.connect(self.stopCurrentConn) quitButton.clicked.connect(self.close) self.webSocket.connected.connect(self.websocketConnect) self.webSocket.disconnected.connect(self.webSocketDisconnect) self.webSocket.error.connect(self.displayError) self.webSocket.textMessageReceived.connect( self.webSocketMessageReceived) self.sendTextEdit.textChanged.connect(self.enableSendMessageButton) self.sendMsgbutton.clicked.connect(self.sendMsgToServer) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostCombo, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(taskCodeLabel, 2, 0) mainLayout.addWidget(self.taskLineEdit, 2, 1) mainLayout.addWidget(self.statusLabel, 3, 0, 1, 2) mainLayout.addWidget(buttonBox, 4, 0, 1, 2) mainLayout.addWidget(self.serverMsgLable, 5, 0) mainLayout.addWidget(self.serverLineEdit, 5, 1, 1, 1) mainLayout.addWidget(self.sendMsgLabel, 6, 0) mainLayout.addWidget(self.sendTextEdit, 6, 1) mainLayout.addWidget(self.sendMsgbutton, 7, 0, 1, 5) self.serverLineEdit.setEnabled(False) self.serverMsgLable.setVisible(False) self.serverLineEdit.setVisible(False) self.sendMsgLabel.setVisible(False) self.sendTextEdit.setVisible(False) self.sendMsgbutton.setEnabled(False) self.sendMsgbutton.setVisible(False) self.setLayout(mainLayout) mainLayout.setSpacing(10) self.setWindowTitle(self.title) self.portLineEdit.setFocus() manager = QNetworkConfigurationManager() if manager.capabilities( ) & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, 'QtProject') settings.beginGroup('QtNetwork') id = settings.value('DefaultNetworkConfiguration') settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.getFortuneButton.setEnabled(False) self.statusLabel.setText("Opening network session.") self.networkSession.open()
def __init__(self, parent=None): super(Client, self).__init__(parent) self.networkSession = None self.blockSize = 0 self.currentFortune = "" hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") self.hostCombo = QComboBox() self.hostCombo.setEditable(True) name = QHostInfo.localHostName() if name != "": self.hostCombo.addItem(name) domain = QHostInfo.localDomainName() if domain != "": self.hostCombo.addItem(name + "." + domain) if name != "localhost": self.hostCombo.addItem("localhost") ipAddressesList = QNetworkInterface.allAddresses() for ipAddress in ipAddressesList: if not ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) for ipAddress in ipAddressesList: if ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostCombo) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.") 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.tcpSocket = QTcpSocket(self) self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.tcpSocket.readyRead.connect(self.readFortune) self.tcpSocket.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostCombo, 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("Fortune Client") self.portLineEdit.setFocus() manager = QNetworkConfigurationManager() if manager.capabilities() & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, "QtProject") settings.beginGroup("QtNetwork") id = settings.value("DefaultNetworkConfiguration") settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.getFortuneButton.setEnabled(False) self.statusLabel.setText("Opening network session.") self.networkSession.open()
def __init__(self, parent=None): super(Client, self).__init__(parent) self.networkSession = None self.blockSize = 0 self.currentFortune = '' hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") self.hostCombo = QComboBox() self.hostCombo.setEditable(True) name = QHostInfo.localHostName() if name != '': self.hostCombo.addItem(name) domain = QHostInfo.localDomainName() if domain != '': self.hostCombo.addItem(name + '.' + domain) if name != 'localhost': self.hostCombo.addItem('localhost') ipAddressesList = QNetworkInterface.allAddresses() for ipAddress in ipAddressesList: if not ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) for ipAddress in ipAddressesList: if ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostCombo) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.") 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.tcpSocket = QTcpSocket(self) self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.tcpSocket.readyRead.connect(self.readFortune) self.tcpSocket.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostCombo, 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("Fortune Client") self.portLineEdit.setFocus() manager = QNetworkConfigurationManager() if manager.capabilities( ) & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, 'QtProject') settings.beginGroup('QtNetwork') id = settings.value('DefaultNetworkConfiguration') settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.getFortuneButton.setEnabled(False) self.statusLabel.setText("Opening network session.") self.networkSession.open()