Example #1
0
    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)
Example #2
0
    def __init__(self):
        super(LoginWindow, self).__init__()

        # 加载ui文件
        loadUi('loginPage.ui', self)

        # 关闭页面 就销毁对象
        self.setAttribute(Qt.WA_DeleteOnClose)
        # 创建udp socket
        self.udp_client_socket = QUdpSocket()
        # 收发数据对象
        self.data = LoginStruct()
        # 注册界面空对象
        self.register_window = None
        # 聊天界面空对象
        self.chat_window = None
        # 后台界面空对象
        self.houtai_window = None

        # 设置背景图片
        background = QPixmap("img/login_background.jpeg")
        # 图片缩放
        background = background.scaled(self.background_label.width(),
                                       self.background_label.width())
        self.background_label.setPixmap(background)
        # 设置输入密码框
        self.passwd_lineEdit.setEchoMode(QLineEdit.Password)

        # 登录按钮接到press_login_btn槽函数
        self.login_Btn.clicked.connect(self.pressLoginBtn)
        # 注册按钮接到press_rgs_btn槽函数
        self.rgs_Btn.clicked.connect(self.pressRgsBtn)
        # 收到服务器消息链接到 receive_message槽函数
        self.udp_client_socket.readyRead.connect(self.receiveMessage)
Example #3
0
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

        self.udpSocket = QUdpSocket()
        self.udpSocket.bind(self.port)
        self.udpSocket.readyRead.connect(self.handle_incoming)
Example #4
0
    def __init__(self):
        super(FileWindow, self).__init__()
        # 加载ui文件
        loadUi('filepage.ui', self)
        # 关闭页面 就销毁对象
        self.setAttribute(Qt.WA_DeleteOnClose)
        # 定义显示在TableWidget中的空对象
        self.newItem0 = None
        self.newItem1 = None

        # 创建定时器对象
        self.timer = QTimer()
        # 创建udp客户端socket
        self.udp_client_socket = QUdpSocket()
        # 上传路径+文件名
        self.file_path_name = ''
        # 下载文件名
        self.file_name = ''

        # 收到服务器消息链接到 receive_message槽函数
        self.udp_client_socket.readyRead.connect(self.receiveMessage)
        # 上传文件按钮点击信号,连接到槽函数
        self.up_btn.clicked.connect(self.pressUpLoadBtn)
        # 下载文件按钮点击信号,连接到槽函数
        self.down_btn.clicked.connect(self.pressDownloadBtn)
        # 定时器超时信号,连接到槽函数
        self.timer.timeout.connect(self.timeout)

        # 初始化TableWidget
        self.initTableWidget()
        # 启动定时器
        self.timer.start(2000)
Example #5
0
    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")
Example #6
0
    def __init__(self, parent=None):
        super(Sender, self).__init__(parent)

        self.statusLabel = QLabel("Ready to broadcast datagrams on port 45454")

        self.startButton = QPushButton("&Start")
        quitButton = QPushButton("&Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.timer = QTimer(self)
        self.udpSocket = QUdpSocket(self)
        self.messageNo = 1

        self.startButton.clicked.connect(self.startBroadcasting)
        quitButton.clicked.connect(self.close)
        self.timer.timeout.connect(self.broadcastDatagramm)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Broadcast Sender")
Example #7
0
    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()
Example #8
0
    def start_trans(self, pipe):
        if self.pipe != pipe:
            return

        print('start_trans %d' % self.pipe)

        if self.SocketClient:
            self.SocketClient.readyRead.disconnect(self.on_readyRead)
            self.SocketClient.connected.disconnect(self.on_connected)
            self.SocketClient.disconnected.disconnect(self.on_disconnected)
            self.SocketClient.error.disconnect(self.on_error)
            self.SocketClient.close()
            self.SocketClient.deleteLater()
            self.SocketClient = None

        if appsetting.trans_protocol(pipe) == 'tcp':
            self.SocketClient = QTcpSocket()
        else:
            self.SocketClient = QUdpSocket()

        self.SocketClient.readyRead.connect(self.on_readyRead)
        self.SocketClient.connected.connect(self.on_connected)
        self.SocketClient.disconnected.connect(self.on_disconnected)
        self.SocketClient.error.connect(self.on_error)

        self.SocketClient.bind(QHostAddress(appsetting.trans_localip(pipe)))
        self.sig_Transing_state.emit(self.pipe, False)
        if appsetting.trans_enable(self.pipe) != '0':
            self.SocketClient.connectToHost(appsetting.trans_ip(pipe), int(appsetting.trans_port(pipe)))
 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())
Example #10
0
    def __init__(self, parent=None):
        super(QObject, self).__init__(parent)

        self.udpSocket = QUdpSocket(self)
        self.udpSocket.readyRead.connect(self.data_received)

        self.__currentIndex = 0
Example #11
0
    def __init__(self):
        super(AudioWindow, self).__init__()
        # 加载ui文件
        loadUi('audioPage.ui', self)

        self.my_count = ''
        self.friend_count = ''

        # 创建socket对象
        self.audio_socket = QUdpSocket()
        # 收到服务器消息链接到 receive_message槽函数
        self.audio_socket.readyRead.connect(self.receiveMessage)

        # 创建audio_data对象
        self.audio_data = AudioStruct()

        # 创建两个线程对象
        self.audio_client = AudioClient()
        self.audio_server = AudioServer()

        # 接受语音消息
        self.recvBtn.clicked.connect(self.pressAcceptBtn)
        # 拒绝语音消息
        self.rejectBtn.clicked.connect(self.pressRejectBtn)
        # 关闭
        self.closeBtn.clicked.connect(self.pressCloseBtn)

        self.set_count_server.connect(self.audio_server.setCount)
        self.set_count_client.connect(self.audio_client.setCount)
Example #12
0
 def network(self):
     #若接收数据正常,udpsocket->bytesAvailable()的值将为0,接收不到数据则为非零值,这样就可用个定时器,是不是的检测下,若不为零,将SOCKET重启即可。
     self.udpSocket = QUdpSocket(self)
     self.port = 12345
     self.udpSocket.bind(
         self.port, QUdpSocket.ShareAddress | QUdpSocket.ReuseAddressHint)
     self.udpSocket.readyRead.connect(self.processPendingDatagrams)
Example #13
0
class Connection:
    """
    A Connection object is an IP connection that reads and processes messages from a UDP client.
    This is developed with the vision-based guidance system in mind, though it is not limited to it. It may
    may also provide a connection to a gamepad or other peripheral system.
    """

    #TODO this Connection class is there as a placeholder.
    # TODO This should migrate to multi-processing/multi-threading, and remove risk of blocking functions

    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 write_message(self, input_message):
        # udp_socket.writeDatagram(b, QHostAddress('192.168.43.1'), port)
        # self.udp_socket.writeDatagram(input_message, self.host_ip, self.port)
        self.udp_socket.writeData(input_message)

    def read_message(self):
        return self.udp_socket.readDatagram(100)
Example #14
0
 def connectToSensorPublisher(self):
     self.sensorpubSocket = QUdpSocket()
     self.sensorpubSocket.bind(QHostAddress.AnyIPv4,
                               self.sensorBroadcastPort,
                               QUdpSocket.ShareAddress)
     self.sensorpubSocket.joinMulticastGroup(self.sensorBroadcastAddress)
     self.lastSensorBroadcastAddress = self.sensorBroadcastAddress
Example #15
0
    def __init__(self, *sources, **kwargs):
        """Arguments:
        sources: paths of QML component sources
        kwargs: passed on to PreviewTab
        """
        super().__init__()

        self._tab_kwargs = kwargs
        self.setWindowTitle("pqp")

        self.tab_widget = QTabWidget()
        self.tab_widget.setTabsClosable(True)
        self._populate_tab_widget(*sources)
        self.load_button = QPushButton("Load...")

        layout = QVBoxLayout()
        layout.addWidget(self.tab_widget)
        layout.addWidget(self.load_button)
        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.udp_socket = QUdpSocket()
        self.udp_socket.bind(QHostAddress.LocalHost, UDP_PORT)

        self.load_button.clicked.connect(self.show_dialog)
        self.udp_socket.readyRead.connect(self.read_from_udp_client)
        self.tab_widget.tabCloseRequested.connect(self.shutdown_tab)
Example #16
0
    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)
Example #17
0
    def __init__(self):
        super(CommSockets, self).__init__()

        self.ourSocket = QUdpSocket(self)
        self.ourSocket.bind(QHostAddress.LocalHost, self.SOCKET_NR_OUR)

        self.theirSocket = QUdpSocket(self)
        self.ourSocket.readyRead.connect(self.readPendingDatagrams)
Example #18
0
    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))
Example #19
0
 def __init__(self):
     super(UdpCore, self).__init__()
     self.initUI()
     '''
     disconnectFromHost, close, abort好像都可以中断udp bind状态
     '''
     self.udpSocket = QUdpSocket(self)
     self.signalSlot()
Example #20
0
    def __init__(self, my_count):
        super(ChatWindow, self).__init__()
        # 关闭页面 就销毁对象
        self.setAttribute(Qt.WA_DeleteOnClose)
        # 加载界面文件
        loadUi("chatPage.ui", self)
        self.my_count = my_count
        self.myname_label.setText(self.my_count)
        # 定时器对象
        self.timer = QTimer()
        # 创建udp客户端socket
        self.udp_client_socket = QUdpSocket()
        # 收发数据对象
        self.data = ChatStruct()
        # 用户列表
        self.user_list = []

        # 聊天记录界面空对象
        self.chat_record_page = None
        # 文件传输界面空对象
        self.file_window = None

        # 设置背景图片
        background = QPixmap("img/chat_background.jpg")
        background = background.scaled(self.back_label.width(),
                                       self.back_label.width())
        self.back_label.setPixmap(background)

        # 设置只读
        self.show_msg_textEdit.setReadOnly(True)

        # 定时器初始化
        self.timer.start(1000)
        # 定时器超时信号,连接到槽函数
        self.timer.timeout.connect(self.timeout)

        # 双击好友treeWidget
        self.friends_treeWidget.doubleClicked.connect(
            self.on_treeWidget_doubleClicked)
        # 发送消息按钮,连接到槽函数
        self.send_Btn.clicked.connect(self.pressSendBtn)
        # 查看聊天记录按钮,连接到槽函数
        self.msg_log_Btn.clicked.connect(self.pressMsgBtn)
        # 文件按钮信号,连接到槽函数
        self.file_up_Btn.clicked.connect(self.pressFileBtn)
        # 收到服务器消息链接到 receiveMessage槽函数
        self.udp_client_socket.readyRead.connect(self.receiveMessage)

        # 语音界面
        self.audio_window = None
        # 语音消息按钮
        self.audio_Btn.clicked.connect(self.pressAudioBtn)

        # 更新ip 和 端口
        self.update_ip_port()
        # 获取好友列表
        self.updateUserList()
class UdpSocket(QObject, ICommunicateTCPIP):
    def __init__(self, parent):
        super(UdpSocket, self).__init__()
        self.udpSocket = QUdpSocket(parent)

    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 send(self, data):
        """
        udp-发送
        :param data: str or bytearray
        :return:
        """
        self.send(data, self.getDstIp(), self.getDstPort())

    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 connectRec(self, slotRec):
        self.udpSocket.readyRead.connect(slotRec)

    def read(self):
        """
        读数据
        :return: bytearray
        """
        data = bytearray()
        while self.udpSocket.hasPendingDatagrams():
            datagram, senderAddress, senderPort = self.udpSocket.readDatagram(
                self.udpSocket.pendingDatagramSize())
            data.extend(datagram)
            self.setRecSrcIp(senderAddress.toString())
            self.setRecSrcPort(senderPort)
        return data

    def close(self):
        self.udpSocket.close()
Example #22
0
 def __init__(self, game_port, login, peer_id, recv):
     QObject.__init__(self)
     self._logger.info("Allocating local relay for {}, {}".format(login, peer_id))
     self._socket = QUdpSocket()
     self._socket.stateChanged.connect(self._state_changed)
     self._socket.readyRead.connect(self._ready_read)
     self.game_port = game_port
     self.login, self.peer_id = login, peer_id
     self.recv = recv
Example #23
0
    def __init__(self):
        super(UdpCommunication, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.udpSocket = QUdpSocket()                              #socket

        self.udpSocket.bind(9999)
        self.ui.pushButton_send.clicked.connect(self.handleSend)
        self.udpSocket.readyRead.connect(self.handleRecv)
 def __init__(self, parent=None):
     super(MainWindow, self).__init__(parent)
     self.setupUi(self)
     self.password_ui = PasswordVerify(mainwindow=self)
     self.face_ui = FaceVerify(mainwindow=self)
     self.find_device = QUdpSocket()
     self.video_send = QUdpSocket()
     self.set_bind()
     self.showFullScreen()
     self.set_connect()
Example #25
0
class Relay(QObject):
    bound = pyqtSignal(int)

    def __init__(self, game_port, login, peer_id, recv):
        QObject.__init__(self)
        self._logger.info("Allocating local relay for {}, {}".format(login, peer_id))
        self._socket = QUdpSocket()
        self._socket.stateChanged.connect(self._state_changed)
        self._socket.readyRead.connect(self._ready_read)
        self.game_port = game_port
        self.login, self.peer_id = login, peer_id
        self.recv = recv

    def listen(self):
        self._socket.bind()

    def send(self, message):
        self._logger.debug("game at 127.0.0.1:{}<<{} len: {}".format(self.game_port, self.peer_id, len(message)))
        self._socket.writeDatagram(message, QHostAddress.LocalHost, self.game_port)

    def _state_changed(self, state):
        if state == QUdpSocket.BoundState:
            self.bound.emit(self._socket.localPort())

    def _ready_read(self):
        while self._socket.hasPendingDatagrams():
            data, host, port = self._socket.readDatagram(self._socket.pendingDatagramSize())
            if data is None:    # Rare race condition when disconnecting
                continue
            self._logger.debug("{}>>{}/{}".format(self._socket.localPort(), self.login, self.peer_id))
            self.recv(data)
Example #26
0
 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
Example #27
0
 def __init__(self,port,service_id):
     self.multicastgroup = QHostAddress("224.0.1.232")
     self.mcast_port = 55421
     self.port = port
     super().__init__()
     self.udpSocket = QUdpSocket(self)
     self.udpSocket.bind(QHostAddress.AnyIPv4,int(port))
     self.udpSocket_multi = QUdpSocket(self)
     self.udpSocket_multi.bind(QHostAddress.AnyIPv4, self.mcast_port, QUdpSocket.ReuseAddressHint)
     self.udpSocket_multi.joinMulticastGroup(self.multicastgroup)
     self.udpSocket.readyRead.connect(self.processPendingDatagrams)
     self.udpSocket_multi.readyRead.connect(self.processPendingDatagrams_multi)
Example #28
0
 def __init__(self, parent=None):
     super(Control, self).__init__(parent)
     self.setupUi(self)
     self.function = "manual_driver"
     self.ip = ""
     self.port = 0
     self.forward_or_back = None
     self.left_or_right = None
     self.holder = None
     self.car_socket = QTcpSocket(self)
     self.monitoring_socket = QUdpSocket(self)
     self.monitoring_socket.bind(QHostAddress("10.42.0.1"), 8889)
     self.connect_to_car()
     self.set_connect()
Example #29
0
 def __init__(self, port, data_cb):
     QUdpSocket.__init__(self)
     self._session = QTurnSession(self)
     self._state = TURNState.UNBOUND
     self.bindings = {}
     self.initial_port = port
     self._data_cb = data_cb
     self.turn_host, self.turn_port = config.Settings.get('turn/host', type=str, default='dev.faforever.com'), \
                            config.Settings.get('turn/port', type=int, default=3478)
     self._logger.info("Turn socket initialized: {}".format(self.turn_host))
     self.turn_address = None
     QHostInfo.lookupHost(self.turn_host, self._looked_up)
     self.bind(port)
     self.readyRead.connect(self._readyRead)
     self.error.connect(self._error)
Example #30
0
class Ui_Form():
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(230, 50)
        Form.setMinimumSize(QtCore.QSize(230, 50))
        Form.setMaximumSize(QtCore.QSize(230, 50))
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(10, 20, 201, 22))
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(10)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_2.setStyleSheet("color:red")
        #程序添加的
        self.status=0
        self.udpSocket = QUdpSocket()     #创建socket
        self.udpSocket.bind(8848)

        self.retranslateUi(Form)
        self.udpSocket.readyRead.connect(self.handleRecv)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def handleRecv(self):
        buf = bytes()
        buf, ip, port = self.udpSocket.readDatagram(1024)
        message = buf.decode()
        self.label_2.setText("distance: %s"%message+" "+"time: "+str(time.strftime("%H:%M:%S",time.localtime())))
        try:
            if len(message)<=8:
                if int(message) >80:
                    if self.status==0:
                        res=ctypes.windll.user32.LockWorkStation()
                        self.status=res
                        print(res)
                    else:
                        pass
                else:
                    self.status=0
            else:
                pass
        except ValueError:
            pass

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Auto Lock"))
        Form.setWindowIcon(QtGui.QIcon('Lock.ico'))
class UdpHandler(QObject):
    """ Listens to a udp port. Default is port 9021 """
    def __init__(self, model, port=9021):
        super().__init__()
        self._model = model
        self._socket = QUdpSocket(self)
        self._socket.bind(QHostAddress.Any, port)
        self._socket.readyRead.connect(self.readDatagrams)

    def readDatagrams(self):
        datagrams = []
        while self._socket.hasPendingDatagrams():
            datagram_size = self._socket.pendingDatagramSize()
            datagram, _, _ = self._socket.readDatagram(datagram_size)
            datagrams.append(datagram)

        records = [convert_datagram(datagram) for datagram in datagrams]
        self._model.add_records(records)
Example #32
0
    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)
Example #33
0
class Receiver(QDialog):
    def __init__(self, parent=None):
        super(Receiver, self).__init__(parent)

        self.statusLabel = QLabel("Listening for broadcasted messages")
        quitButton = QPushButton("&Quit")

        self.udpSocket = QUdpSocket(self)
        self.udpSocket.bind(45454)

        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 processPendingDatagrams(self):
        while self.udpSocket.hasPendingDatagrams():
            datagram, host, port = self.udpSocket.readDatagram(self.udpSocket.pendingDatagramSize())

            try:
                # Python v3.
                datagram = str(datagram, encoding='ascii')
            except TypeError:
                # Python v2.
                pass

            self.statusLabel.setText("Received datagram: \"%s\"" % datagram)
Example #34
0
class Sender(QDialog):
    def __init__(self, parent=None):
        super(Sender, self).__init__(parent)

        self.statusLabel = QLabel("Ready to broadcast datagrams on port 45454")

        self.startButton = QPushButton("&Start")
        quitButton = QPushButton("&Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.timer = QTimer(self)
        self.udpSocket = QUdpSocket(self)
        self.messageNo = 1

        self.startButton.clicked.connect(self.startBroadcasting)
        quitButton.clicked.connect(self.close)
        self.timer.timeout.connect(self.broadcastDatagramm)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Broadcast Sender")

    def startBroadcasting(self):
        self.startButton.setEnabled(False)
        self.timer.start(1000)

    def broadcastDatagramm(self):
        self.statusLabel.setText("Now broadcasting datagram %d" % self.messageNo)
        datagram = "Broadcast message %d" % self.messageNo
        self.udpSocket.writeDatagram(datagram, QHostAddress(QHostAddress.Broadcast), 45454)
        self.messageNo += 1
Example #35
0
    def __init__(self, parent=None):
        super(Receiver, self).__init__(parent)

        self.statusLabel = QLabel("Listening for broadcasted messages")
        quitButton = QPushButton("&Quit")

        self.udpSocket = QUdpSocket(self)
        self.udpSocket.bind(45454)

        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")
Example #36
0
    secondUDP_IP = covise.getCoConfigEntry("vr-prepare.SecondUDP.IP")
    if secondUDP_IP:
        host = QHostAddress(secondUDP_IP)
    else:
        host = QHostAddress("127.0.0.1")
    secondUDP_Port = covise.getCoConfigEntry("vr-prepare.SecondUDP.Port")
    if secondUDP_Port:
        port = int(secondUDP_Port)
    else:
        port = 6666
    buf = 1024
    addr = (host,port)

    # Create socket and bind to address
    if covise.coConfigIsOn("vr-prepare.SecondUDP"):
        UDPSock = QUdpSocket() 
        UDPSock.bind(port)
        udpMode = True
except:
    pass
#--------


#
# receiver thread filling up the global message queue
#
class Rec(Thread):
#================
    lastInfo_ = ""
    
    def __init__(self,queue):        
 def __init__(self, model, port=9021):
     super().__init__()
     self._model = model
     self._socket = QUdpSocket(self)
     self._socket.bind(QHostAddress.Any, port)
     self._socket.readyRead.connect(self.readDatagrams)
Example #38
0
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)
Example #39
-1
    def __init__(self, parent=None):
        super(Sender, self).__init__(parent)

        self.statusLabel = QLabel("Ready to broadcast datagrams on port 45454")

        self.startButton = QPushButton("&Start")
        quitButton = QPushButton("&Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.timer = QTimer(self)
        self.udpSocket = QUdpSocket(self)
        self.messageNo = 1

        self.startButton.clicked.connect(self.startBroadcasting)
        quitButton.clicked.connect(self.close)
        self.timer.timeout.connect(self.broadcastDatagramm)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Broadcast Sender")