Example #1
0
    def sendMessage(self):
        """
        发送文件
        """
        self.serverSendBtn.setEnabled(False)
        self.clientConnection = self.tcpServer.nextPendingConnection()
        self.clientConnection.bytesWritten.connect(self.updateClientProgress)
        self.serverStatuslabel.setText("开始传送文件 {} !".format(self.theFileName))

        self.localFile = QFile(self.fileName)
        if not (self.localFile.open(QFile.ReadOnly)):
            errorMsg = "无法读取文件 {}:\n {}".format(self.fileName,
                                                self.localFile.errorString())
            QMessageBox.warning(self, "应用程序", errorMsg)
            return

        self.serverCloseBtn.setText("取消")

        self.totalBytes = self.localFile.size()  #单位:字节
        sendOut = QDataStream(self.outBlock, QIODevice.WriteOnly)
        sendOut.setVersion(QDataStream.Qt_5_4)
        self.time.start()
        currentFile = self.fileName.split("/")[-1]
        sendOut.writeInt64(0)
        sendOut.writeInt64(0)
        sendOut.writeQString(currentFile)
        self.totalBytes += self.outBlock.size()
        sendOut.device().seek(0)
        sendOut.writeInt64(self.totalBytes)
        sendOut.writeInt64(self.outBlock.size() - 2)
        self.bytesToWrite = self.totalBytes - self.clientConnection.write(
            self.outBlock)
        self.outBlock.resize(0)
Example #2
0
    def sendBackFile(self, socket, filePath):  #
        file = QFile(filePath)
        print(file.size())
        count = 0
        with open(filePath, 'rb') as f:
            while 1:
                sleep(0.1)
                filedata = f.read(20480)
                if not filedata:
                    break
                reply = QByteArray()
                stream = QDataStream(reply, QIODevice.WriteOnly)
                stream.setVersion(QDataStream.Qt_5_7)
                stream.writeUInt16(0)

                stream.writeQString('SENDFILE')
                stream.writeQString(file.fileName())
                stream.writeInt(file.size())
                stream.writeBytes(filedata)

                stream.device().seek(0)
                stream.writeUInt16(reply.size() - SIZEOF_UINT16)
                socket.write(reply)
                socket.waitForBytesWritten()
                count = count + filedata.__len__()
                print(count)
Example #3
0
    def testCurvePlotItemArray2Path(self):
        size = 5
        x = np.arange(size)
        y = 2 * np.arange(size)
        item = CurvePlotItem(x, y)
        self._widget.addItem(item)
        p = item._graph

        # stream path
        arr = QByteArray()
        buf = QDataStream(arr, QIODevice.ReadWrite)
        buf << p
        buf.device().reset()

        # test protocol
        assert arr.size() == 4 + size * 20 + 8
        assert buf.readInt32() == size
        for i in range(5):
            if i == 0:
                assert buf.readInt32() == 0
            else:
                assert buf.readInt32() == 1
            assert buf.readDouble() == x[i]
            assert buf.readDouble() == y[i]
        assert buf.readInt32() == 0
        assert buf.readInt32() == 0
Example #4
0
 def dealCommunication(self):
     # Get a QTcpSocket from the QTcpServer
     clientConnection = self.tcpServer.nextPendingConnection()
     # instantiate a QByteArray
     block = QByteArray()
     # QDataStream class provides serialization of binary data to a QIODevice
     out = QDataStream(block, QIODevice.ReadWrite)
     # We are using PyQt5 so set the QDataStream version accordingly.
     out.setVersion(QDataStream.Qt_5_0)
     out.writeUInt16(0)
     # this is the message we will send it could come from a widget.
     message = "ACK!"
     # get a byte array of the message encoded appropriately.
     message = bytes(message, encoding='ascii')
     # now use the QDataStream and write the byte array to it.
     out.writeString(message)
     out.device().seek(0)
     out.writeUInt16(block.size() - 2)
     # wait until the connection is ready to read
     while True:
         clientConnection.waitForReadyRead()
         # read incomming data
         instr = clientConnection.readAll()
         # in this case we print to the terminal could update text of a widget if we wanted.
         data = str(instr, encoding='ascii')
         print(data)
         if data.strip() == "END":
             break
         clientConnection.write(block)
     clientConnection.disconnected.connect(clientConnection.deleteLater)
     clientConnection.disconnectFromHost()
Example #5
0
    def send(self):
        self.byte2write = self.localfile.size()
        self.totalsize = self.localfile.size()

        self.loadsize = 4 * 1024

        out = QDataStream(self.outblock, QtCore.QIODevice.WriteOnly)
        current_filename = self.filename.split("/")[-1]

        out.writeInt64(0)
        out.writeInt64(0)

        self.totalsize += self.outblock.size()
        self.byte2write += self.outblock.size()

        out.writeQString(current_filename)
        out.device().seek(0)
        out.writeInt64(self.totalsize)
        out.writeInt64(self.outblock.size())

        self.socket.write(self.outblock)

        self.psbar.show()
        self.psbar.setMaximum(self.totalsize)
        self.psbar.setValue(self.totalsize - self.byte2write)
Example #6
0
    def sendMessage(self):
        """
        发送文件
        """
        self.serverSendBtn.setEnabled(False)
        # 发送按钮不可用

        self.clientConnection = self.tcpServer.nextPendingConnection()
        # self.clientConnection作为连接的QTcpSocket对象返回下一个挂起的连接。

        self.clientConnection.bytesWritten.connect(self.updateClientProgress)
        # 当连接中每次将数据有效载荷写入设备的当前写通道时,都会发出此信号。在此有效负载中写入的数据量为字节数。

        self.serverStatuslabel.setText("开始传送文件 {} !".format(self.theFileName))

        self.localFile = QFile(self.fileName)
        if not (self.localFile.open(QFile.ReadOnly)):
            errorMsg = "无法读取文件 {}:\n {}".format(self.fileName,
                                                self.localFile.errorString())
            QMessageBox.warning(self, "应用程序", errorMsg)
            return
        # 尝试打开文件,要是存在问题就报错。

        self.serverCloseBtn.setText("取消")

        self.totalBytes = self.localFile.size()
        # 记录一下需要传输的文件大小。单位:字节

        sendOut = QDataStream(self.outBlock, QIODevice.WriteOnly)
        # 这里的self.outBlock是QByteArray()的对象,即字节数组;QIODevice的模式为WriteOnly

        sendOut.setVersion(QDataStream.Qt_5_4)
        # 设定QDataStream的版本为Qt_5_4

        self.time.start()
        # 开始计时

        currentFile = self.fileName.split("/")[-1]
        # 传输的文件名

        sendOut.writeInt64(0)
        sendOut.writeInt64(0)
        sendOut.writeQString(currentFile)
        self.totalBytes += self.outBlock.size()
        # 在sendOut中写入文件名以及文件名和文件的大小,大小都是以字节为单位的。

        sendOut.device().seek(0)
        sendOut.writeInt64(self.totalBytes)
        sendOut.writeInt64(self.outBlock.size() - 2)
        # QIODevice读写位置移动到0。然后分别写入总的大小和文件名大小。

        self.bytesToWrite = self.totalBytes - self.clientConnection.write(
            self.outBlock)
        # 待传输文件的大小。

        self.outBlock.resize(0)
Example #7
0
 def slot_send(self, event_msg):
     reply = QByteArray()
     stream = QDataStream(reply, QIODevice.WriteOnly)
     stream.writeUInt16(0)
     # stream.writeQString(event_id)
     stream.writeQString(event_msg)
     stream.writeUInt16(0)
     stream.device().seek(0)
     stream.writeUInt16(reply.size() - SIZE_OF_UINT16)
     self.write(reply)
Example #8
0
 def sendError(self, socket, msg):
   reply = QByteArray()
   stream = QDataStream(reply, QIODevice.WriteOnly)
   stream.setVersion(QDataStream.Qt_5_7)
   stream.writeUInt16(0)
   stream.writeQString("ERROR")
   stream.writeQString(msg)
   stream.device().seek(0)
   stream.writeUInt16(reply.size() - SIZEOF_UINT16)
   socket.write(reply)
Example #9
0
 def sendBackOrder(self, socket, order):  # 回传一条命令
     reply = QByteArray()
     stream = QDataStream(reply, QIODevice.WriteOnly)
     stream.setVersion(QDataStream.Qt_5_7)
     stream.writeUInt16(0)
     stream.writeQString("ORDER")  # 回传一条命令,命令自己定义。
     stream.writeQString(order)
     stream.device().seek(0)
     stream.writeUInt16(reply.size() - SIZEOF_UINT16)
     socket.write(reply)
     socket.waitForBytesWritten()
Example #10
0
 def sendReply(self, socket, action, room, date):
   reply = QByteArray()
   stream = QDataStream(reply, QIODevice.WriteOnly)
   stream.setVersion(QDataStream.Qt_5_7)
   stream.writeUInt16(0)
   stream.writeQString(action)
   stream.writeQString(room)
   stream<<date
   stream.device().seek(0)
   stream.writeUInt16(reply.size() - SIZEOF_UINT16)
   socket.write(reply)
Example #11
0
 def sendReply(self, socket):  # 用于测试
     reply = QByteArray()
     stream = QDataStream(reply, QIODevice.WriteOnly)
     stream.setVersion(QDataStream.Qt_5_7)
     stream.writeUInt16(0)
     stream.writeQString("test")
     stream.writeQString('收到')
     stream.device().seek(0)
     stream.writeUInt16(reply.size() - SIZEOF_UINT16)
     socket.write(reply)
     socket.waitForBytesWritten()
Example #12
0
 def wrapper(self, *args, **kwargs):
     request = QByteArray()
     stream = QDataStream(request, QIODevice.WriteOnly)
     stream.setVersion(QDataStream.Qt_5_7)
     stream.writeUInt64(0)
     # time.sleep(0.1)
     result = func(self, stream, *args, **kwargs)
     stream.device().seek(0)
     stream.writeUInt64(request.size() - SIZEOF_UINT64)
     self.socket.write(request)
     self.socket.waitForBytesWritten()
     return result
Example #13
0
 def sendMessage(self, qheaer):
     # print("server send",qheaer)
     self.outBlock = QByteArray()
     sendout = QDataStream(self.outBlock, QIODevice.WriteOnly)
     sendout.setVersion(QDataStream.Qt_5_4)
     sendout.writeInt64(0)  #占位
     sendout.writeQString(qheaer)
     headBytes = self.outBlock.size()
     sendout.device().seek(0)
     sendout.writeInt64(headBytes - SIZEOF_HEAD_INT)
     # sendout.writeInt64(0)
     self.write(self.outBlock)  #head
Example #14
0
    def sendHeaderMsg(self, qheader):
        self.outBlock = QByteArray()
        sendout = QDataStream(self.outBlock, QIODevice.WriteOnly)
        sendout.setVersion(QDataStream.Qt_5_4)
        sendout.writeInt64(0)  #占位
        sendout.writeInt64(0)

        sendout.writeQString(qheader)
        headBytes = self.outBlock.size()

        sendout.device().seek(0)
        sendout.writeInt64(headBytes - SIZEOF_HEAD_INT)
        self.tcpSocket.write(self.outBlock)  #head
Example #15
0
def serialize(items):
    """Serialize a list of WebHistoryItems to a data stream.

    Args:
        items: An iterable of WebHistoryItems.

    Return:
        A (stream, data, user_data) tuple.
            stream: The reset QDataStream.
            data: The QByteArray with the raw data.
            cur_user_data: The user data for the current item or None.

    Warning:
        If 'data' goes out of scope, reading from 'stream' will result in a
        segfault!
    """
    data = QByteArray()
    stream = QDataStream(data, QIODevice.ReadWrite)
    cur_user_data = None

    current_idx = None

    for i, item in enumerate(items):
        if item.active:
            if current_idx is not None:
                raise ValueError("Multiple active items ({} and {}) "
                                 "found!".format(current_idx, i))
            current_idx = i
            cur_user_data = item.user_data

    if items:
        if current_idx is None:
            raise ValueError("No active item found!")
    else:
        current_idx = -1

    ### src/core/web_contents_adapter.cpp serializeNavigationHistory
    #                                          sample data:
    # kHistoryStreamVersion
    stream.writeInt(HISTORY_STREAM_VERSION)  # \x00\x00\x00\x03
    # count
    stream.writeInt(len(items))  # \x00\x00\x00\x01
    # currentIndex
    stream.writeInt(current_idx)  # \x00\x00\x00\x00

    for item in items:
        _serialize_item(item, stream)

    stream.device().reset()
    qtutils.check_qdatastream(stream)
    return stream, data, cur_user_data
    def sendFortune(self):
        block = QByteArray()
        out = QDataStream(block, QIODevice.WriteOnly)
        out.setVersion(QDataStream.Qt_4_0)
        out.writeUInt16(0)
        out.writeQString(random.choice(self.fortunes))
        out.device().seek(0)
        out.writeUInt16(block.size() - 2)

        clientConnection = self.server.nextPendingConnection()
        clientConnection.disconnected.connect(clientConnection.deleteLater)
        clientConnection.write(block)
        clientConnection.flush()
        clientConnection.disconnectFromServer()
    def my_send_signal(self, inp_text):
        """
        发送交易指令到MT4的Files文件夹,或发送到交易服务器
        """
        # 读取配置文件到字典变量
        if len(self.config) == 0:
            self.config = self.my_read_config()
        mode = self.config[1]

        if mode == 'Local':
            symbols = ['EURUSD', 'GBPUSD', 'XAUUSD', 'USDJPY']
            for symbol in symbols:
                if inp_text.find(symbol) >= 0:
                    trade_symbol = symbol
            file_path = self.config[2]
            # 检查交易品种的子文件夹是否存在,不存在就新建相应的子文件夹
            if os.path.exists(file_path + '\\' + trade_symbol) == False:
                os.mkdir(file_path + '\\' + trade_symbol)

            file_path = file_path + '\\' + trade_symbol + '\\'

            # 将指令存到对应的子文件夹里
            file_name = file_path + 'trade_signal.txt'

            with open(file_name, 'w') as file_object:
                file_object.write(inp_text)

        # 将交易指令传到交易服务器上
        elif mode == 'Network':
            account_number = self.config[0]
            host = self.config[2]
            port = int(self.config[3])

            self.request = QByteArray()
            stream = QDataStream(self.request, QIODevice.WriteOnly)
            stream.writeUInt16(0)
            stream.writeQString(account_number)
            stream.writeQString(inp_text)
            stream.device().seek(0)
            stream.writeUInt16(self.request.size() - SIZEOF_UINT16)

            self.my_updateUI()

            if self.socket.isOpen():
                self.socket.close()
            self.socket.connectToHost(host, port)

            rec_text = my_cur_time() + ' 正在连接远程交易服务器...'
            self.statusBar().showMessage(rec_text)
            my_operating_record(rec_text)
Example #18
0
    def sendFortune(self):
        block = QByteArray()
        out = QDataStream(block, QIODevice.WriteOnly)
        out.setVersion(QDataStream.Qt_4_0)
        out.writeUInt16(0)
        out.writeQString(random.choice(self.fortunes))
        out.device().seek(0)
        out.writeUInt16(block.size() - 2)

        clientConnection = self.server.nextPendingConnection()
        clientConnection.disconnected.connect(clientConnection.deleteLater)
        clientConnection.write(block)
        clientConnection.flush()
        clientConnection.disconnectFromServer()
Example #19
0
def serialize(items):
    """Serialize a list of QWebHistoryItems to a data stream.

    Args:
        items: An iterable of WebHistoryItems.

    Return:
        A (stream, data, user_data) tuple.
            stream: The reset QDataStream.
            data: The QByteArray with the raw data.
            cur_user_data: The user data for the current item or None.

    Warning:
        If 'data' goes out of scope, reading from 'stream' will result in a
        segfault!
    """
    data = QByteArray()
    stream = QDataStream(data, QIODevice.ReadWrite)
    cur_user_data = None

    current_idx = None

    for i, item in enumerate(items):
        if item.active:
            if current_idx is not None:
                raise ValueError("Multiple active items ({} and {}) "
                                 "found!".format(current_idx, i))
            current_idx = i
            cur_user_data = item.user_data

    if items:
        if current_idx is None:
            raise ValueError("No active item found!")
    else:
        current_idx = -1

    ### src/core/web_contents_adapter.cpp serializeNavigationHistory
    # kHistoryStreamVersion
    stream.writeInt(HISTORY_STREAM_VERSION)
    # count
    stream.writeInt(len(items))
    # currentIndex
    stream.writeInt(current_idx)

    for item in items:
        _serialize_item(item, stream)

    stream.device().reset()
    qtutils.check_qdatastream(stream)
    return stream, data, cur_user_data
Example #20
0
 def sendMessage(self, text, socket):
     # for s in self.connections:
     self.reply = QByteArray()
     stream = QDataStream(self.reply, QIODevice.WriteOnly)
     stream.setVersion(QDataStream.Qt_4_9)
     stream.writeUInt32(0)
     stream.writeUInt32(0) # header for QString
     stream.writeQString(f"{text}")
     stream.device().seek(0)
     stream.writeUInt32(self.reply.size() - SIZEOF_UINT32)
     
     socket.write(self.reply)
     self.reply = None
     print(f"sending '{text}' to {socket.socketDescriptor()}")
     socket.waitForBytesWritten(1000)
Example #21
0
    def my_sendReply(self, socket, inp_text):
        reply = QByteArray()
        stream = QDataStream(reply, QIODevice.WriteOnly)
        stream.writeUInt16(0)
        stream.writeQString(inp_text)
        stream.device().seek(0)
        stream.writeUInt16(reply.size() - SIZEOF_UINT16)
        socket.write(reply)

        try:
            self.lock.lockForWrite()
            rec_text = my_cur_time() + ' 已将交易指令{0}的接收情况反馈给客户端!'.format(inp_text)
            self.recordSignal.sendSignal.emit(rec_text)
        finally:
            self.lock.unlock()
Example #22
0
 def issueRequest(self, action, room, date):
     self.request = QByteArray()
     stream = QDataStream(self.request, QIODevice.WriteOnly)
     stream.setVersion(QDataStream.Qt_5_7)
     stream.writeUInt16(0)
     stream.writeQString(action)
     stream.writeQString(room)
     stream << date
     stream.device().seek(0)
     stream.writeUInt16(self.request.size() - SIZEOF_UINT16)
     self.updateUi()
     if self.socket.isOpen():
         self.socket.close()
     self.responseLabel.setText("Connecting to server...")
     self.socket.connectToHost("localhost", PORT)
Example #23
0
def serialize(items):
    """Serialize a list of QWebHistoryItems to a data stream.

    Args:
        items: An iterable of WebHistoryItems.

    Return:
        A (stream, data, user_data) tuple.
            stream: The reset QDataStream.
            data: The QByteArray with the raw data.
            user_data: A list with each item's user data.

    Warning:
        If 'data' goes out of scope, reading from 'stream' will result in a
        segfault!
    """
    data = QByteArray()
    stream = QDataStream(data, QIODevice.ReadWrite)
    user_data = []

    current_idx = None

    for i, item in enumerate(items):
        if item.active:
            if current_idx is not None:
                raise ValueError("Multiple active items ({} and {}) "
                                 "found!".format(current_idx, i))
            else:
                current_idx = i

    if items:
        if current_idx is None:
            raise ValueError("No active item found!")
    else:
        current_idx = 0

    ### Source/WebKit/qt/Api/qwebhistory.cpp operator<<
    stream.writeInt(HISTORY_STREAM_VERSION)
    stream.writeInt(len(items))
    stream.writeInt(current_idx)

    for i, item in enumerate(items):
        _serialize_item(i, item, stream)
        user_data.append(item.user_data)

    stream.device().reset()
    qtutils.check_qdatastream(stream)
    return stream, data, user_data
Example #24
0
def serialize(items):
    """Serialize a list of QWebHistoryItems to a data stream.

    Args:
        items: An iterable of WebHistoryItems.

    Return:
        A (stream, data, user_data) tuple.
            stream: The reseted QDataStream.
            data: The QByteArray with the raw data.
            user_data: A list with each item's user data.

    Warning:
        If 'data' goes out of scope, reading from 'stream' will result in a
        segfault!
    """
    data = QByteArray()
    stream = QDataStream(data, QIODevice.ReadWrite)
    user_data = []

    current_idx = None

    for i, item in enumerate(items):
        if item.active:
            if current_idx is not None:
                raise ValueError("Multiple active items ({} and {}) "
                                 "found!".format(current_idx, i))
            else:
                current_idx = i

    if items:
        if current_idx is None:
            raise ValueError("No active item found!")
    else:
        current_idx = 0

    ### Source/WebKit/qt/Api/qwebhistory.cpp operator<<
    stream.writeInt(HISTORY_STREAM_VERSION)
    stream.writeInt(len(items))
    stream.writeInt(current_idx)

    for i, item in enumerate(items):
        _serialize_item(i, item, stream)
        user_data.append(item.user_data)

    stream.device().reset()
    qtutils.check_qdatastream(stream)
    return stream, data, user_data
Example #25
0
    def sendMessage(self):
        self.request = QByteArray()
        stream = QDataStream(self.request, QIODevice.WriteOnly)
        stream.setVersion(QDataStream.Qt_4_9)
        stream.writeUInt32(0)
        stream.writeUInt32(0)  # HEADER: this is a QString

        stream.writeQString(f"{self.text}")

        stream.device().seek(0)
        stream.writeUInt32(self.request.size() - self.SIZEOF_UINT32)
        self.write(self.request)
        self.nextBlockSize = 0
        self.request = None
        print(f"sending '{self.text}' to Server")
        self.messageSent.emit("[SENT] " + self.text)
Example #26
0
    def sendFortune(self):
        fortune = self.FORTUNES[random.randint(0, len(self.FORTUNES) - 1)]

        block = QByteArray()
        out = QDataStream(block, QIODevice.WriteOnly)
        out.setVersion(QDataStream.Qt_4_0)
        out.writeUInt16(0)
        out.writeQString(fortune)
        out.device().seek(0)
        out.writeUInt16(block.size() - 2)

        clientConnection = self.tcpServer.nextPendingConnection()
        clientConnection.disconnected.connect(clientConnection.deleteLater)

        clientConnection.write(block)
        clientConnection.disconnectFromHost()
    def sendFortune(self):
        fortune = self.FORTUNES[random.randint(0, len(self.FORTUNES) - 1)]

        block = QByteArray()
        out = QDataStream(block, QIODevice.WriteOnly)
        out.setVersion(QDataStream.Qt_4_0)
        out.writeUInt16(0)
        out.writeQString(fortune)
        out.device().seek(0)
        out.writeUInt16(block.size() - 2)

        clientConnection = self.tcpServer.nextPendingConnection()
        clientConnection.disconnected.connect(clientConnection.deleteLater)

        clientConnection.write(block)
        clientConnection.disconnectFromHost()
Example #28
0
    def dealCommunication(self):
        # Get a QTcpSocket from the QTcpServer
        clientConnection = self.tcpServer.nextPendingConnection()

        # instantiate a QByteArray
        block = QByteArray()

        # QDataStream class provides serialization of binary data to a QIODevice
        out = QDataStream(block, QIODevice.ReadWrite)

        # We are using PyQt5 so set the QDataStream version accordingly.
        out.setVersion(QDataStream.Qt_5_0)
        out.writeUInt16(0)

        # this is the message we will send it could come from a widget.
        message = "ok"

        # get a byte array of the message encoded appropriately.
        message = bytes(message, encoding='ascii')

        # now use the QDataStream and write the byte array to it.
        out.writeString(message)
        out.device().seek(0)
        out.writeUInt16(block.size() - 2)

        # wait until the connection is ready to read
        clientConnection.waitForReadyRead()

        # read incomming data
        instr = clientConnection.readAll()

        # in this case we print to the terminal could update text of a widget if we wanted.
        # data = str(instr, encoding='ascii')
        data = instr
        data = np.frombuffer(data, dtype=np.uint)
        print("Get ", data, " from client")

        # get the connection ready for clean up
        clientConnection.disconnected.connect(clientConnection.deleteLater)

        # now send the QByteArray.
        # clientConnection.write(block)

        # now disconnect connection.
        clientConnection.disconnectFromHost()
        print("Disconnection")
    def run(self):
        tcpSocket = QTcpSocket()
        if not tcpSocket.setSocketDescriptor(self.socketDescriptor):
            self.error.emit(tcpSocket.error())
            return

        block = QByteArray()
        outstr = QDataStream(block, QIODevice.WriteOnly)
        outstr.setVersion(QDataStream.Qt_4_0)
        outstr.writeUInt16(0)
        outstr.writeQString(self.text)
        outstr.device().seek(0)
        outstr.writeUInt16(block.size() - 2)

        tcpSocket.write(block)
        tcpSocket.disconnectFromHost()
        tcpSocket.waitForDisconnected()
    def run(self):
        tcpSocket = QTcpSocket()
        if not tcpSocket.setSocketDescriptor(self.socketDescriptor):
            self.error.emit(tcpSocket.error())
            return

        block = QByteArray()
        outstr = QDataStream(block, QIODevice.WriteOnly)
        outstr.setVersion(QDataStream.Qt_4_0)
        outstr.writeUInt16(0)
        outstr.writeQString(self.text)
        outstr.device().seek(0)
        outstr.writeUInt16(block.size() - 2)

        tcpSocket.write(block)
        tcpSocket.disconnectFromHost()
        tcpSocket.waitForDisconnected()
Example #31
0
def serialize(items):
    """Serialize a list of QWebHistoryItems to a data stream.

    Args:
        items: An iterable of WebHistoryItems.

    Return:
        A (stream, data, user_data) tuple.
            stream: The reset QDataStream.
            data: The QByteArray with the raw data.
            user_data: A list with each item's user data.

    Warning:
        If 'data' goes out of scope, reading from 'stream' will result in a
        segfault!
    """
    data = QByteArray()
    stream = QDataStream(data, QIODevice.ReadWrite)
    user_data = []

    current_idx = None

    for i, item in enumerate(items):
        if item.active:
            if current_idx is not None:
                raise ValueError("Multiple active items ({} and {}) "
                                 "found!".format(current_idx, i))
            else:
                current_idx = i

    if items:
        if current_idx is None:
            raise ValueError("No active item found!")
    else:
        current_idx = 0

    if qtutils.is_qtwebkit_ng():
        _serialize_ng(items, current_idx, stream)
    else:
        _serialize_old(items, current_idx, stream)

    user_data += [item.user_data for item in items]

    stream.device().reset()
    qtutils.check_qdatastream(stream)
    return stream, data, user_data
Example #32
0
    def slot_send(self, event_msg):
        print("send")
        print(event_msg)
        # 定义一个字节列表
        reply = QByteArray()
        # 使用QDateaStream向列表写入
        stream = QDataStream(reply, QIODevice.WriteOnly)
        # 为什么接受的最小长度是2个字节,是因为这里收尾都写入了0
        stream.writeUInt16(0)
        # stream.writeQString(event_id)
        stream.writeQString(event_msg)
        stream.writeUInt16(0)

        # 寻找到首部的0,写入字节流的真实长度
        stream.device().seek(0)
        stream.writeUInt16(reply.size() - SIZE_OF_UINT16)

        # 发送
        self.write(reply)
Example #33
0
    def sendImage(self):
        self.request = QByteArray()
        stream = QDataStream(self.request, QIODevice.WriteOnly)
        stream.setVersion(QDataStream.Qt_4_9)
        stream.writeUInt32(0)
        stream.writeUInt32(1)  # HEADER: this is an QImage

        ba = QByteArray()
        buffer = QBuffer(ba)
        self.img = QImage()
        self.img.load(f"{self.text}")
        self.img.save(buffer, "PNG")  # writes image into ba in PNG format
        stream.writeBytes(ba)

        stream.device().seek(0)
        stream.writeUInt32(self.request.size() - self.SIZEOF_UINT32)
        self.write(self.request)
        self.nextBlockSize = 0
        self.request = None
        print(f"sending '{self.text}' to Server")
        self.messageSent.emit("[SENT] " + self.text)
Example #34
0
    def send_msg(self):
        block = QByteArray()
        # QDataStream class provides serialization of binary data to a QIODevice
        out = QDataStream(block, QIODevice.ReadWrite)
        # We are using PyQt5 so set the QDataStream version accordingly.
        out.setVersion(QDataStream.Qt_5_0)
        out.writeUInt16(0)
        text_box_msg = self.textbox.text()
        to = ""
        msg = ""
        if "@" not in text_box_msg:
            print(
                "TO whom should I send a message? use e.g. @all Hello all or @Max Hello max"
            )
            return
        else:
            to, msg = text_box_msg.split(' ',
                                         1)[0], text_box_msg.split(' ', 1)[1]
            to = to.replace("@", "")

        # get a byte array of the message encoded appropriately.
        message = bytes(msg, encoding='ascii')
        # now use the QDataStream and write the byte array to it.
        out.writeString(message)
        out.device().seek(0)
        out.writeUInt16(block.size() - 2)
        aaa = True
        if to == "all":
            for conn in self.clientConnections:
                conn["conn"].write(block)
        else:
            for conn in self.clientConnections:
                if conn["name"] == to:
                    conn["conn"].write(block)
                    aaa = False
        if aaa:
            print("Sry I server could not send message to", to)
Example #35
0
    def readRequest(self):
        stream = QDataStream(self)
        stream.setVersion(QDataStream.Qt_5_7)
        #print(self.bytesAvailable())
        if self.nextBlockSize == 0:
            if self.bytesAvailable() < SIZEOF_UINT16:
                return
            self.nextBlockSize = stream.readUInt16()
            #print(self.nextBlockSize)
        if self.bytesAvailable() < self.nextBlockSize:
            return

        action = ""
        room = ""
        date = QDate()
        action=stream.readQString()
        if action in ("BOOK", "UNBOOK", "BOOKINGSONDATE",
                      "BOOKINGSFORROOM"):
            room=stream.readQString()
            stream >> date            
            bookings = Bookings.get(date.toPyDate())
            uroom = str(room)
        if action == "BOOK":
            if bookings is None:
                bookings = Bookings[date.toPyDate()]
            if len(bookings) < MAX_BOOKINGS_PER_DAY:
                if uroom in bookings:
                    self.sendError("Cannot accept duplicate booking")
                else:
                    bisect.insort(bookings, uroom)
                    self.sendReply(action, room, date)
            else:
                self.sendError("{0} is fully booked".format(date.toString(Qt.ISODate)))
        elif action == "UNBOOK":
            if bookings is None or uroom not in bookings:
                self.sendError("Cannot unbook nonexistent booking")
            else:
                bookings.remove(uroom)
                self.sendReply(action, room, date)
        elif action == "BOOKINGSONDATE":
            bookings = Bookings.get(date.toPyDate())
            if bookings is not None:
                self.sendReply(action, ", ".join(bookings), date)
            else:
                self.sendError("there are no rooms booked on {0}".format(date.toString(Qt.ISODate)))
        elif action == "BOOKINGSFORROOM":
            dates = []
            for date, bookings in Bookings.items():
                if room in bookings:
                    dates.append(date)
            if dates:
                dates.sort()
                reply = QByteArray()
                stream = QDataStream(reply, QIODevice.WriteOnly)
                stream.setVersion(QDataStream.Qt_5_7)
                stream.writeUInt16(0)
                stream.writeQString(action)
                stream.writeQString(room)
                stream.writeInt32(len(dates))
                for date in dates:
                    stream << QDate(date)
                stream.device().seek(0)
                stream.writeUInt16(reply.size() - SIZEOF_UINT16)
                self.write(reply)
            else:
                self.sendError("room %1 is not booked".format(room))
        else:
            self.sendError("Unrecognized request")
        printBookings()