Example #1
0
    def restoreState(self, state):
        """
        Public method to restore the state of the sidebar.
        
        @param state byte array containing the saved state (QByteArray)
        @return flag indicating success (boolean)
        """
        if state.isEmpty():
            return False

        if self.__orientation in [E5SideBar.North, E5SideBar.South]:
            minSize = self.layout.minimumSize().height()
            maxSize = self.maximumHeight()
        else:
            minSize = self.layout.minimumSize().width()
            maxSize = self.maximumWidth()

        data = QByteArray(state)
        stream = QDataStream(data, QIODevice.ReadOnly)
        stream.setVersion(QDataStream.Qt_4_6)
        version = stream.readUInt16()  # version
        minimized = stream.readBool()

        if minimized and not self.__minimized:
            self.shrink()

        stream >> self.__bigSize
        if version == 1:
            self.__minSize = max(stream.readUInt16(), minSize)
            self.__maxSize = max(stream.readUInt16(), maxSize)
            count = stream.readUInt16()
            self.splitterSizes = []
            for _ in range(count):
                self.splitterSizes.append(stream.readUInt16())
        elif version == 2:
            self.__minSize = max(stream.readUInt32(), minSize)
            self.__maxSize = max(stream.readUInt32(), maxSize)
            count = stream.readUInt32()
            self.splitterSizes = []
            for _ in range(count):
                self.splitterSizes.append(stream.readUInt32())

        self.__autoHide = stream.readBool()
        self.__autoHideButton.setChecked(not self.__autoHide)

        if not minimized:
            self.expand()

        return True
Example #2
0
    def loadCookies(self, cookies):
        """
        Public method to restore the saved cookies.
        
        @param cookies byte array containing the saved cookies (QByteArray)
        @return list of cookies
        """
        if cookies.isEmpty():
            return []

        cookiesList = []
        data = QByteArray(cookies)
        stream = QDataStream(data, QIODevice.ReadOnly)
        stream.setVersion(QDataStream.Qt_4_6)

        version = stream.readUInt16()
        if version != self.JAR_VERSION:
            return []

        stream.readUInt32()  # number of cookies

        rawCookie = QByteArray()
        while not stream.atEnd():
            stream >> rawCookie
            newCookies = QNetworkCookie.parseCookies(rawCookie)
            for newCookie in newCookies:
                cookiesList.append(newCookie)

        return cookiesList
    def readResponse(self):
        stream = QDataStream(self.socket)
        stream.setVersion(QDataStream.Qt_5_7)

        while True:
            if self.nextBlockSize == 0:
                if self.socket.bytesAvailable() < SIZEOF_UINT16:
                    break
                self.nextBlockSize = stream.readUInt16()
            if self.socket.bytesAvailable() < self.nextBlockSize:
                break
            action = ""
            room = ""
            date = QDate()
            #stream >> action >> room
            action = stream.readQString()
            room = stream.readQString()
            if action != "ERROR":
                stream >> date
            if action == "ERROR":
                msg = "Error: {0}".format(room)
            elif action == "BOOK":
                msg = "Booked room {0} for {1}".format(
                    room, date.toString(Qt.ISODate))
            elif action == "UNBOOK":
                msg = "Unbooked room {0} for {1}".format(
                    room, date.toString(Qt.ISODate))
            self.responseLabel.setText(msg)
            self.updateUi()
            self.nextBlockSize = 0
    def my_readResponse(self):
        stream = QDataStream(self.socket)

        while True:
            if self.nextBlockSize == 0:
                if self.socket.bytesAvailable() < SIZEOF_UINT16:
                    break
                self.nextBlockSize = stream.readUInt16()
            if self.socket.bytesAvailable() < self.nextBlockSize:
                break

            ser_reply = stream.readQString()

            if ser_reply == 'None':
                QMessageBox.critical(self, '错误提示!', self.tr('您没有开通服务器交易功能!'))
                rec_text = my_cur_time() + ' 您没有开通服务器交易功能!'
                self.statusBar().showMessage(rec_text)
                my_operating_record(rec_text)
            else:
                rec_text = my_cur_time() + ' 服务器已接收指令:{0}'.format(ser_reply)
                self.statusBar().showMessage(rec_text)
                my_operating_record(rec_text)

            self.nextBlockSize = 0
            self.socket.close()
            self.my_updateUI()
            rec_text = my_cur_time() + ' 已断开服务器连接!'
            my_operating_record(rec_text)
Example #5
0
 def loadCookies(self, cookies):
     """
     Public method to restore the saved cookies.
     
     @param cookies byte array containing the saved cookies (QByteArray)
     @return list of cookies
     """
     if cookies.isEmpty():
         return []
     
     cookiesList = []
     data = QByteArray(cookies)
     stream = QDataStream(data, QIODevice.ReadOnly)
     stream.setVersion(QDataStream.Qt_4_6)
     
     version = stream.readUInt16()
     if version != self.JAR_VERSION:
         return []
     
     stream.readUInt32()  # number of cookies
     
     rawCookie = QByteArray()
     while not stream.atEnd():
         stream >> rawCookie
         newCookies = QNetworkCookie.parseCookies(rawCookie)
         for newCookie in newCookies:
             cookiesList.append(newCookie)
     
     return cookiesList
Example #6
0
 def dealCommunication(self):
     instr = QDataStream(self.tcpSocket)
     instr.setVersion(QDataStream.Qt_5_0)
     if self.blockSize == 0:
         if self.tcpSocket.bytesAvailable() < 2:
             return
         self.blockSize = instr.readUInt16()
     if self.tcpSocket.bytesAvailable() < self.blockSize:
         return
     # Print response to terminal, we could use it anywhere else we wanted.
     print(str(instr.readString(), encoding='ascii'))
Example #7
0
 def restoreState(self, state):
     """
     Public method to restore the state of the sidebar.
     
     @param state byte array containing the saved state (QByteArray)
     @return flag indicating success (boolean)
     """
     if state.isEmpty():
         return False
     
     if self.__orientation in [E5SideBar.North, E5SideBar.South]:
         minSize = self.layout.minimumSize().height()
         maxSize = self.maximumHeight()
     else:
         minSize = self.layout.minimumSize().width()
         maxSize = self.maximumWidth()
     
     data = QByteArray(state)
     stream = QDataStream(data, QIODevice.ReadOnly)
     stream.setVersion(QDataStream.Qt_4_6)
     stream.readUInt16()  # version
     minimized = stream.readBool()
     
     if minimized and not self.__minimized:
         self.shrink()
     
     stream >> self.__bigSize
     self.__minSize = max(stream.readUInt16(), minSize)
     self.__maxSize = max(stream.readUInt16(), maxSize)
     count = stream.readUInt16()
     self.splitterSizes = []
     for i in range(count):
         self.splitterSizes.append(stream.readUInt16())
     
     self.__autoHide = stream.readBool()
     self.__autoHideButton.setChecked(not self.__autoHide)
     
     if not minimized:
         self.expand()
     
     return True
Example #8
0
    def readResponse(self):  # 收命令,要做的事情,

        stream = QDataStream(self.socket)
        print('--------------------')
        print('服务器响应')
        stream.setVersion(QDataStream.Qt_5_7)

        while True:
            self.nextBlockSize = 0
            if self.nextBlockSize == 0:
                if self.socket.bytesAvailable() < SIZEOF_UINT16:
                    print('没有内容了')
                    break
                self.nextBlockSize = stream.readUInt16()

            else:
                print('错误')  # 客户端主动断开时,去掉字典中的对应,在这里做一部分操作。
                # 客户端主动断开的时候,要将其从self.myParent.sockeIdToSocketDict   self.myParent.fixIdToSocketIdDict 中删掉

                break
            if self.socket.bytesAvailable() < self.nextBlockSize:
                print("错误2")
                if (not self.socket.waitForReadyRead(60000)
                        or self.socket.bytesAvailable() < self.nextBlockSize):
                    break
            state = stream.readQString()  # 读命令         sendModel
            print('state==' + state)
            if state == 'SENDFILE':
                filename = stream.readQString()  # 读文件名
                fileSize = stream.readInt()  # 读文件大小
                with open('../TEST/' + filename, 'ab') as f:
                    while self.nextBlockSize > 0:
                        fileBytes = stream.readBytes()  # 读文件部分字节
                        f.write(fileBytes)

                        print(fileBytes.__len__())
                        self.nextBlockSize = stream.readUInt64()
                        print('self.nextBlockSize:' + str(self.nextBlockSize))
                        state = stream.readQString()
                        filename = stream.readQString()  # 读文件名
                        fileSize = stream.readInt()  # 读文件大小
                        print('filename:' + filename)
                        print('fileSize:' + str(fileSize))

            elif state == 'test':
                print(stream.readQString())

            elif state == 'ORDER':  # 收到一条命令      要执行的命令
                order = stream.readQString()  # 读是什么命令
                if order:  # shou dao doThing
                    self.doSomeThing.emit(order)
Example #9
0
    def _recvResponse(self, socket):
        data = b""
        while not self._stop_event.is_set():
            new_data = socket.recv(64)
            if len(new_data) == 0:
                break
            data += new_data

        block = QByteArray(data)
        stream = QDataStream(block)
        stream.setVersion(QDataStream.Qt_4_0)
        blocksize = stream.readUInt16()
        resp = stream.readQString()

        return resp
Example #10
0
    def slot_receive(self):
        print("recv")
        min_block_size = SIZE_OF_UINT16
        while self.state() == QAbstractSocket.ConnectedState:
            stream = QDataStream(self)

            if self.bytesAvailable() >= min_block_size:
                nextblock_size = stream.readUInt16()

            else:
                break
            if nextblock_size < min_block_size:
                break
            # Event_id = stream.readQString()
            Event_msg = stream.readQString()
            print(Event_msg)
            self.sign_recv.emit(Event_msg)
Example #11
0
    def slot_readyRead(self):
        # 定义最小接受长度
        print("come")
        min_block_size = SIZE_OF_UINT16

        while self.state() == QAbstractSocket.ConnectedState:
            stream = QDataStream(self)
            # 如果可接受字符串比这个更小就直接丢弃
            if self.bytesAvailable() >= min_block_size:
                # 读取接下来信息流的长度,因为信息流第一个位置写入的是长度,为UInt16类型
                nextblock_size = stream.readUInt16()
            else:
                break
            # 如果 nextblock_size 比这个还小说明接受错误
            if nextblock_size <= min_block_size:
                break
            # event_id = stream.readQString()
            event_msg = stream.readQString()
            self.sign_recv.emit(event_msg)
    def readFortune(self):
        ins = QDataStream(self.socket)
        ins.setVersion(QDataStream.Qt_4_0)

        if self.blockSize == 0:
            if self.socket.bytesAvailable() < 2:
                return
            self.blockSize = ins.readUInt16()

        if ins.atEnd():
            return

        nextFortune = ins.readQString()
        if nextFortune == self.currentFortune:
            QTimer.singleShot(0, self.requestNewFortune)
            return

        self.currentFortune = nextFortune
        self.statusLabel.setText(self.currentFortune)
        self.getFortuneButton.setEnabled(True)
Example #13
0
    def readFortune(self):
        ins = QDataStream(self.socket)
        ins.setVersion(QDataStream.Qt_4_0)

        if self.blockSize == 0:
            if self.socket.bytesAvailable() < 2:
                return
            self.blockSize = ins.readUInt16()

        if ins.atEnd():
            return

        nextFortune = ins.readQString()
        if nextFortune == self.currentFortune:
            QTimer.singleShot(0, self.requestNewFortune)
            return

        self.currentFortune = nextFortune
        self.statusLabel.setText(self.currentFortune)
        self.getFortuneButton.setEnabled(True)
Example #14
0
    def readResponse(self):
        stream = QDataStream(self.socket)
        stream.setVersion(QDataStream.Qt_5_7)

        while True:
            if self.nextBlockSize == 0:
                if self.socket.bytesAvailable() < SIZEOF_UINT16:
                    break
                self.nextBlockSize = stream.readUInt16()
            if self.socket.bytesAvailable() < self.nextBlockSize:
                break
            action = ""
            room = ""
            date = QDate()
            action = stream.readQString()
            room = stream.readQString()
            if action == "BOOKINGSFORROOM":
                dates = []
                for x in range(stream.readInt32()):
                    stream >> date
                    dates.append(str(date.toString(Qt.ISODate)))
                dates = ", ".join(dates)
            if action not in ("BOOKINGSFORROOM", "ERROR"):
                stream >> date
            if action == "ERROR":
                msg = "Error: {0}".format(room)
            elif action == "BOOK":
                msg = "Booked room {0} for {1}".format(
                    room, date.toString(Qt.ISODate))
            elif action == "UNBOOK":
                msg = "Unbooked room {0} for {1}".format(
                    room, date.toString(Qt.ISODate))
            elif action == "BOOKINGSONDATE":
                msg = "Rooms booked on {0}: {1}".format(
                    date.toString(Qt.ISODate), room)
            elif action == "BOOKINGSFORROOM":
                msg = "Room {0} is booked on: {1}".format(room, dates)
            self.responseLabel.setText(msg)
            self.updateUi()
            self.nextBlockSize = 0
    def run(self):
        self.mutex.lock()
        serverName = self.hostName
        serverPort = self.port
        self.mutex.unlock()

        while not self.quit:
            Timeout = 5 * 1000

            socket = QTcpSocket()
            socket.connectToHost(serverName, serverPort)

            if not socket.waitForConnected(Timeout):
                self.error.emit(socket.error(), socket.errorString())
                return

            while socket.bytesAvailable() < 2:
                if not socket.waitForReadyRead(Timeout):
                    self.error.emit(socket.error(), socket.errorString())
                    return

            instr = QDataStream(socket)
            instr.setVersion(QDataStream.Qt_4_0)
            blockSize = instr.readUInt16()

            while socket.bytesAvailable() < blockSize:
                if not socket.waitForReadyRead(Timeout):
                    self.error.emit(socket.error(), socket.errorString())
                    return

            self.mutex.lock()
            fortune = instr.readQString()
            self.newFortune.emit(fortune)

            self.cond.wait(self.mutex)
            serverName = self.hostName
            serverPort = self.port
            self.mutex.unlock()
    def run(self):
        self.mutex.lock()
        serverName = self.hostName
        serverPort = self.port
        self.mutex.unlock()

        while not self.quit:
            Timeout = 5 * 1000

            socket = QTcpSocket()
            socket.connectToHost(serverName, serverPort)

            if not socket.waitForConnected(Timeout):
                self.error.emit(socket.error(), socket.errorString())
                return

            while socket.bytesAvailable() < 2:
                if not socket.waitForReadyRead(Timeout):
                    self.error.emit(socket.error(), socket.errorString())
                    return 

            instr = QDataStream(socket)
            instr.setVersion(QDataStream.Qt_4_0)
            blockSize = instr.readUInt16()

            while socket.bytesAvailable() < blockSize:
                if not socket.waitForReadyRead(Timeout):
                    self.error.emit(socket.error(), socket.errorString())
                    return

            self.mutex.lock()
            fortune = instr.readQString()
            self.newFortune.emit(fortune)

            self.cond.wait(self.mutex)
            serverName = self.hostName
            serverPort = self.port
            self.mutex.unlock()
Example #17
0
    def restoreState(self, state, version=0):
        """
        Public method to restore the state of the toolbar manager.
        
        @param state byte array containing the saved state (QByteArray)
        @param version version number stored with the data (integer)
        @return flag indicating success (boolean)
        """
        if state.isEmpty():
            return False

        data = QByteArray(state)
        stream = QDataStream(data, QIODevice.ReadOnly)
        stream.setVersion(QDataStream.Qt_4_6)
        marker = stream.readUInt16()
        vers = stream.readUInt16()
        if marker != E5ToolBarManager.VersionMarker or vers != version:
            return False

        tmarker = stream.readUInt16()
        if tmarker != E5ToolBarManager.ToolBarMarker:
            return False

        toolBarCount = stream.readUInt16()
        for i in range(toolBarCount):
            objectName = Utilities.readStringFromStream(stream)
            actionCount = stream.readUInt16()
            actions = []
            for j in range(actionCount):
                actionName = Utilities.readStringFromStream(stream)
                if actionName:
                    action = self.__findAction(actionName)
                    if action is not None:
                        actions.append(action)
                else:
                    actions.append(None)
            toolBar = self.__findDefaultToolBar(objectName)
            if toolBar is not None:
                self.setToolBar(toolBar, actions)

        cmarker = stream.readUInt16()
        if cmarker != E5ToolBarManager.CustomToolBarMarker:
            return False

        oldCustomToolBars = self.__customToolBars[:]

        toolBarCount = stream.readUInt16()
        for i in range(toolBarCount):
            objectName = Utilities.readStringFromStream(stream)
            toolBarTitle = Utilities.readStringFromStream(stream)
            actionCount = stream.readUInt16()
            actions = []
            for j in range(actionCount):
                actionName = Utilities.readStringFromStream(stream)
                if actionName:
                    action = self.__findAction(actionName)
                    if action is not None:
                        actions.append(action)
                else:
                    actions.append(None)
            toolBar = self.__toolBarByName(objectName)
            if toolBar is not None:
                toolBar.setWindowTitle(toolBarTitle)
                oldCustomToolBars.remove(toolBar)
            else:
                toolBar = self.createToolBar(toolBarTitle, objectName)
            if toolBar is not None:
                toolBar.setObjectName(objectName)
                self.setToolBar(toolBar, actions)

        for tb in oldCustomToolBars:
            self.deleteToolBar(tb)

        return True
Example #18
0
 def restoreState(self, state, version=0):
     """
     Public method to restore the state of the toolbar manager.
     
     @param state byte array containing the saved state (QByteArray)
     @param version version number stored with the data (integer)
     @return flag indicating success (boolean)
     """
     if state.isEmpty():
         return False
     
     data = QByteArray(state)
     stream = QDataStream(data, QIODevice.ReadOnly)
     stream.setVersion(QDataStream.Qt_4_6)
     marker = stream.readUInt16()
     vers = stream.readUInt16()
     if marker != E5ToolBarManager.VersionMarker or vers != version:
         return False
     
     tmarker = stream.readUInt16()
     if tmarker != E5ToolBarManager.ToolBarMarker:
         return False
     
     toolBarCount = stream.readUInt16()
     for i in range(toolBarCount):
         objectName = Utilities.readStringFromStream(stream)
         actionCount = stream.readUInt16()
         actions = []
         for j in range(actionCount):
             actionName = Utilities.readStringFromStream(stream)
             if actionName:
                 action = self.__findAction(actionName)
                 if action is not None:
                     actions.append(action)
             else:
                 actions.append(None)
         toolBar = self.__findDefaultToolBar(objectName)
         if toolBar is not None:
             self.setToolBar(toolBar, actions)
     
     cmarker = stream.readUInt16()
     if cmarker != E5ToolBarManager.CustomToolBarMarker:
         return False
     
     oldCustomToolBars = self.__customToolBars[:]
     
     toolBarCount = stream.readUInt16()
     for i in range(toolBarCount):
         objectName = Utilities.readStringFromStream(stream)
         toolBarTitle = Utilities.readStringFromStream(stream)
         actionCount = stream.readUInt16()
         actions = []
         for j in range(actionCount):
             actionName = Utilities.readStringFromStream(stream)
             if actionName:
                 action = self.__findAction(actionName)
                 if action is not None:
                     actions.append(action)
             else:
                 actions.append(None)
         toolBar = self.__toolBarByName(objectName)
         if toolBar is not None:
             toolBar.setWindowTitle(toolBarTitle)
             oldCustomToolBars.remove(toolBar)
         else:
             toolBar = self.createToolBar(toolBarTitle, objectName)
         if toolBar is not None:
             toolBar.setObjectName(objectName)
             self.setToolBar(toolBar, actions)
     
     for tb in oldCustomToolBars:
         self.deleteToolBar(tb)
     
     return True
Example #19
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()
Example #20
0
 def run(self):
   socket = QTcpSocket()
   if not socket.setSocketDescriptor(self.socketId):
     #self.emit(SIGNAL("error(int)"), socket.error())
     self.error.connect(socket.error)
     return
   while socket.state() == QAbstractSocket.ConnectedState:
     nextBlockSize = 0
     stream = QDataStream(socket)
     stream.setVersion(QDataStream.Qt_5_7)
     if (socket.waitForReadyRead() and
       socket.bytesAvailable() >= SIZEOF_UINT16):
       nextBlockSize = stream.readUInt16()
     else:
       self.sendError(socket, "Cannot read client request")
       return
     if socket.bytesAvailable() < nextBlockSize:
       if (not socket.waitForReadyRead(60000) or
         socket.bytesAvailable() < nextBlockSize):
         self.sendError(socket, "Cannot read client data")
         return
     action = ""
     room = ""
     date = QDate()
     action=stream.readQString()
     if action in ("BOOK", "UNBOOK"):
       room=stream.readQString()
       stream >> date
       try:
         Thread.lock.lockForRead()
         bookings = Bookings.get(date.toPyDate())
       finally:
         Thread.lock.unlock()
       uroom = str(room)
     if action == "BOOK":
       newlist = False
       try:
         Thread.lock.lockForRead()
         if bookings is None:
           newlist = True
       finally:
         Thread.lock.unlock()
       if newlist:
         try:
           Thread.lock.lockForWrite()
           bookings = Bookings[date.toPyDate()]
         finally:
           Thread.lock.unlock()
       error = None
       insert = False
       try:
         Thread.lock.lockForRead()
         if len(bookings) < MAX_BOOKINGS_PER_DAY:
           if uroom in bookings:
             error = "Cannot accept duplicate booking"
           else:
             insert = True
         else:
           error = "{0} is fully booked".format(date.toString(Qt.ISODate))
       finally:
         Thread.lock.unlock()
       if insert:
         try:
           Thread.lock.lockForWrite()
           bisect.insort(bookings, uroom)
         finally:
           Thread.lock.unlock()
         self.sendReply(socket, action, room, date)
       else:
         self.sendError(socket, error)
     elif action == "UNBOOK":
       error = None
       remove = False
       try:
         Thread.lock.lockForRead()
         if bookings is None or uroom not in bookings:
           error = "Cannot unbook nonexistent booking"
         else:
           remove = True
       finally:
         Thread.lock.unlock()
       if remove:
         try:
           Thread.lock.lockForWrite()
           bookings.remove(uroom)
         finally:
           Thread.lock.unlock()
         self.sendReply(socket, action, room, date)
       else:
         self.sendError(socket, error)
     else:
       self.sendError(socket, "Unrecognized request")
     socket.waitForDisconnected()
     try:
       Thread.lock.lockForRead()
       printBookings()
     finally:
       Thread.lock.unlock()
Example #21
0
    def run(self):
        socket = QTcpSocket()
        if not socket.setSocketDescriptor(self.socketId):
            self.error.connect(socket.error)
            return
        while socket.state() == QAbstractSocket.ConnectedState:
            nextBlockSize = 0
            stream = QDataStream(socket)
            if socket.waitForReadyRead() and \
                    socket.bytesAvailable() >= SIZEOF_UINT16:
                nextBlockSize = stream.readUInt16()
            else:
                rec_text = ' 无法正常读取客户端的请求!'
                rec_text = my_cur_time() + rec_text
                try:
                    self.lock.lockForWrite()
                    self.recordSignal.sendSignal.emit(rec_text)
                finally:
                    self.lock.unlock()
                return

            if socket.bytesAvailable() < nextBlockSize:
                if not socket.waitForReadyRead(5000) or \
                        socket.bytesAvailable() < nextBlockSize:
                    rec_text = ' 无法正常读取客户端的数据!'
                    rec_text = my_cur_time() + rec_text
                    try:
                        self.lock.lockForWrite()
                        self.recordSignal.sendSignal.emit(rec_text)
                    finally:
                        self.lock.unlock()
                    return

            # MT4交易账号
            account_number = stream.readQString()
            if re.match(r'^[1-9]\d+$', account_number):
                # 交易指令
                trade_instruction = stream.readQString()
                rec_text = my_cur_time() + ' 已读取到来自 {0} 的交易指令:{1}'.format(
                    account_number, trade_instruction)
                try:
                    self.lock.lockForWrite()
                    self.recordSignal.sendSignal.emit(rec_text)
                finally:
                    self.lock.unlock()

                if account_number in account_dir.keys():
                    # 将交易信号复制到列表中每个MT4交易账户里
                    for cur_directory in account_dir.values():
                        file_path = cur_directory
                        # 将交易指令存到相应账号MT4的Files文件夹里
                        symbols = ['EURUSD', 'GBPUSD', 'XAUUSD', 'USDJPY']
                        for symbol in symbols:
                            if trade_instruction.find(symbol) >= 0:
                                trade_symbol = symbol
                        # 检查交易品种的子文件夹是否存在,不存在就新建相应的子文件夹
                        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(trade_instruction)
                    reply_text = trade_instruction
                else:
                    reply_text = 'None'
                    rec_text = my_cur_time(
                    ) + ' 交易账号 {0} 没有获得交易服务器的授权!'.format(account_number)
                    try:
                        self.lock.lockForWrite()
                        self.recordSignal.sendSignal.emit(rec_text)
                    finally:
                        self.lock.unlock()

                try:
                    self.lock.lockForWrite()
                    rec_text = my_cur_time() + ' 已将交易指令存到相应的MT4的Files文件夹里!'
                    self.recordSignal.sendSignal.emit(rec_text)
                finally:
                    self.lock.unlock()

                self.my_sendReply(socket, reply_text)
                socket.waitForDisconnected()
            else:
                rec_text = ' 接收到非正常的数据,可能是网络攻击!'
                rec_text = my_cur_time() + rec_text
                try:
                    self.lock.lockForWrite()
                    self.recordSignal.sendSignal.emit(rec_text)
                finally:
                    self.lock.unlock()
Example #22
0
class QmyMainWindow(QMainWindow): 
   def __init__(self, parent=None):
      super().__init__(parent)    #调用父类构造函数,创建窗体
      self.ui=Ui_MainWindow()     #创建UI对象
      self.ui.setupUi(self)       #构造UI界面

      self.ui.groupBox.setEnabled(False)
      self.ui.actSaveALL.setEnabled(False)
      self.ui.actReadALL.setEnabled(False)

      self.setWindowTitle("二进制文件流化读写")
      
      self.__testFileName=""   #测试用文件的文件名
      
##  ==============自定义功能函数============
   def __iniWrite(self):     ##初始化写文件操作
      self.fileDevice=QFile(self.__testFileName)    #创建文件对象
      if  not self.fileDevice.open(QIODevice.WriteOnly):
         del self.fileDevice    #删除对象
         return False

      self.fileStream=QDataStream(self.fileDevice)   #流对象

      self.fileStream.setVersion(QDataStream.Qt_5_12)   #设置版本号,写入和读取的版本号要兼容
      if self.ui.radio_BigEndian.isChecked():
         self.fileStream.setByteOrder(QDataStream.BigEndian)
      else:
         self.fileStream.setByteOrder(QDataStream.LittleEndian)

      ##必须要设置精度,float和double都按照这个精度
      precision=QDataStream.DoublePrecision
      if self.ui.radio_Single.isChecked(): 
         precision=QDataStream.SinglePrecision
      self.fileStream.setFloatingPointPrecision(precision)
      return True

   def __delFileStream(self): ##结束写文件操作
      self.fileDevice.close()
      del self.fileStream
      del self.fileDevice


   def __iniRead(self):  ##开始读文件操作
      if not QFile.exists(self.__testFileName):
         QMessageBox.critical(self,"错误","文件不存在")
         return False
      
      self.fileDevice=QFile(self.__testFileName)    #创建文件对象
      if  not self.fileDevice.open(QIODevice.ReadOnly):
         del self.fileDevice    #删除对象
         return False

      self.fileStream=QDataStream(self.fileDevice)
      self.fileStream.setVersion(QDataStream.Qt_5_12)   #设置流版本号,写入和读取的版本号要兼容

      if self.ui.radio_BigEndian.isChecked():
         self.fileStream.setByteOrder(QDataStream.BigEndian)
      else:
         self.fileStream.setByteOrder(QDataStream.LittleEndian)

      ##必须要设置精度,float和double都按照这个精度
      precision=QDataStream.DoublePrecision
      if self.ui.radio_Single.isChecked(): 
         precision=QDataStream.SinglePrecision
      self.fileStream.setFloatingPointPrecision(precision)

      return True
          
##  ==========由connectSlotsByName() 自动连接的槽函数==================
   
   @pyqtSlot()    ##选择测试用文件
   def on_btnFile_clicked(self):  
      curPath=QDir.currentPath()       #当前目录
      title="选择文件"                 #对话框标题
      filt="流数据文件(*.stream)"     #文件过滤器
      fileName,flt=QFileDialog.getSaveFileName(self,title,curPath,filt)
      if (fileName == ""):
         return

      self.__testFileName=fileName     #测试用文件
      self.ui.editFilename.setText(fileName)
      self.ui.groupBox.setEnabled(True)
      self.ui.actSaveALL.setEnabled(True)
      self.ui.actReadALL.setEnabled(True)


   @pyqtSlot()   ##写  int8
   def on_btnInt8_Write_clicked(self):  
      Value=self.ui.spin_Int8.value() #Python int
      if self.__iniWrite():
         try:
            self.fileStream.writeInt8(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeInt8()出现错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  int8
   def on_btnInt8_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readInt8()
         self.ui.edit_Int8.setText("%d"%Value)
         self.__delFileStream()

   @pyqtSlot()   ##写  uint8
   def on_btnUInt8_Write_clicked(self):  
      Value=self.ui.spin_UInt8.value()
      if self.__iniWrite(): 
         try:
            self.fileStream.writeUInt8(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeUInt8()出现错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  uint8
   def on_btnUInt8_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readUInt8()
         self.ui.edit_UInt8.setText("%d"%Value)
         self.__delFileStream()


   @pyqtSlot()    ##写int16
   def on_btnInt16_Write_clicked(self):  
      Value=self.ui.spin_Int16.value()       #Python的int
      if self.__iniWrite():
         try:
            self.fileStream.writeInt16(Value)   #以int16类型写入文件
         except Exception as e:
            QMessageBox.critical(self, "writeInt16()发生错误", str(e))
         finally:
            self.__delFileStream()
##            print("finally被执行")
          
   @pyqtSlot()    ##读 int16
   def on_btnInt16_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readInt16() 
            self.ui.edit_Int16.setText("%d"%Value)
         except Exception as e:
            QMessageBox.critical(self, "readInt16()发生错误", str(e))
         finally:
            self.__delFileStream()
##            print("finally被执行")
            
            
   @pyqtSlot()   ##写  uint16
   def on_btnUInt16_Write_clicked(self):  
      Value=self.ui.spin_UInt16.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeUInt16(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeUInt16()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  uint16
   def on_btnUIn16_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readUInt16()
         self.ui.edit_UInt16.setText("%d"%Value)
         self.__delFileStream()

         
   @pyqtSlot()   ##写  int32
   def on_btnInt32_Write_clicked(self):  
      Value=self.ui.spin_Int32.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeInt32(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeInt32()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  int32
   def on_btnInt32_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readInt32()
         self.ui.edit_Int32.setText("%d"%Value)
         self.__delFileStream()


   @pyqtSlot()   ##写  int64
   def on_btnInt64_Write_clicked(self):  
      Value=self.ui.spin_Int64.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeInt64(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeInt64()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  int64
   def on_btnInt64_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readInt64()
         self.ui.edit_Int64.setText("%d"%Value)
         self.__delFileStream()


   @pyqtSlot()   ##写  int
   def on_btnInt_Write_clicked(self):  
      Value=self.ui.spin_Int.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeInt(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeInt()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  int
   def on_btnInt_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readInt()
         self.ui.edit_Int.setText("%d"%Value)
         self.__delFileStream()


   @pyqtSlot()   ##写  bool
   def on_btnBool_Write_clicked(self):  
      Value=self.ui.chkBox_In.isChecked() #bool型
      if self.__iniWrite(): 
         self.fileStream.writeBool(Value)
         self.__delFileStream()
          
   @pyqtSlot()    ##读  bool
   def on_btnBool_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readBool() #bool型
         self.ui.chkBox_Out.setChecked(Value)
         self.__delFileStream()


   @pyqtSlot()   ##写  float
   def on_btnFloat_Write_clicked(self):  
      Value=self.ui.spin_Float.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeFloat(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeFloat()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  float
   def on_btnFloat_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readFloat()
            self.ui.edit_Float.setText("%.4f"%Value)
         except Exception as e:
            QMessageBox.critical(self, "writeFloat()发生错误", str(e))
         finally:
            self.__delFileStream()


   @pyqtSlot()   ##写  double
   def on_btnDouble_Write_clicked(self):  
      Value=self.ui.spin_Double.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeDouble(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeDouble()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  double
   def on_btnDouble_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readDouble()
            self.ui.edit_Double.setText("%.4f"%Value)
         except Exception as e:
            QMessageBox.critical(self, "readDouble()发生错误", str(e))
         finally:
            self.__delFileStream()


   @pyqtSlot()    ##写 QString,与Python的str兼容
   def on_btnQStr_Write_clicked(self):  
      Value=self.ui.editQStr_In.text()
      if self.__iniWrite():
         try:
            self.fileStream.writeQString(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeQString()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读 QString,与Python的str兼容
   def on_btnQStr_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readQString()
            self.ui.editQStr_Out.setText(Value)
         except Exception as e:
            QMessageBox.critical(self, "readQString()发生错误", str(e))
         finally:
            self.__delFileStream()

   @pyqtSlot()    ##写 String
   def on_btnStr_Write_clicked(self):  
      strV=self.ui.editStr_In.text()   #str类型
      if self.__iniWrite():
         try:
            bts=bytes(strV,encoding="utf-8")  #转换为bytes类型
            self.fileStream.writeString(bts)
         except Exception as e:
            QMessageBox.critical(self, "写入时发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读 String
   def on_btnStr_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readString()  #bytes类型
            strV=Value.decode("utf-8")          #从bytes类型解码为字符串,编码utf-8
            self.ui.editStr_Out.setText(strV)
         except Exception as e:
            QMessageBox.critical(self, "读取时发生错误", str(e))
         finally:
            self.__delFileStream()

##===字体的写入与读取
   @pyqtSlot()   ##选择字体
   def on_btnFont_In_clicked(self):  
      font=self.ui.btnFont_In.font()
      font,OK=QFontDialog.getFont(font,self) #选择字体
      if OK:
         self.ui.btnFont_In.setFont(font)

   @pyqtSlot()   ##写  QVariant, QFont
   def on_btnFont_Write_clicked(self):  
      font=self.ui.btnFont_In.font()    #QFont类型
      if self.__iniWrite(): 
         self.fileStream.writeQVariant(font)  #QFont类型
         self.__delFileStream()
          
   @pyqtSlot()    ##读  QVariant, QFont
   def on_btnFont_Read_clicked(self):  
      if self.__iniRead():
         try:
            font=self.fileStream.readQVariant()   #QFont类型
            self.ui.editFont_Out.setFont(font)
         except Exception as e:
            QMessageBox.critical(self, "读取时发生错误", str(e))
         finally:
            self.__delFileStream()


##===颜色的写入与读取
   @pyqtSlot()   ##选择颜色
   def on_btnColor_In_clicked(self):  
      plet=self.ui.btnColor_In.palette()  #QPalette
      color=plet.buttonText().color()     #QColor
      color= QColorDialog.getColor(color,self)
      if color.isValid():
         plet.setColor(QPalette.ButtonText,color)
         self.ui.btnColor_In.setPalette(plet)


   @pyqtSlot()   ##写  QVariant, QColor
   def on_btnColor_Write_clicked(self):  
      plet=self.ui.btnColor_In.palette()  
      color=plet.buttonText().color()     #QColor
      if self.__iniWrite(): 
         self.fileStream.writeQVariant(color)  #QColor
         self.__delFileStream()
          
   @pyqtSlot()    ##读  QVariant, QColor
   def on_btnColor_Read_clicked(self):  
      if self.__iniRead():
         try:
            color=self.fileStream.readQVariant()   #读取为QColor类型
            plet=self.ui.editColor_Out.palette() 
            plet.setColor(QPalette.Text,color)
            self.ui.editColor_Out.setPalette(plet)
         except Exception as e:
            QMessageBox.critical(self, "读取时发生错误", str(e))
         finally:
            self.__delFileStream()

   @pyqtSlot()    ##读出编辑框全清空
   def on_actClearOutput_triggered(self):  
      self.ui.edit_Int8.clear()
      self.ui.edit_UInt8.clear()
      self.ui.edit_Int16.clear()
      self.ui.edit_UInt16.clear()
      self.ui.edit_Int32.clear()
      self.ui.edit_Int64.clear()
      self.ui.edit_Int.clear()

      self.ui.edit_Float.clear()
      self.ui.edit_Double.clear()

      font=self.font()
      self.ui.editFont_Out.setFont(font)

      plet=self.palette()
      self.ui.editColor_Out.setPalette(plet)

   @pyqtSlot()    ##连续写入文件
   def on_actSaveALL_triggered(self):  
      if not self.__iniWrite():
         QMessageBox.critical(self,"错误","为写入打开文件时出错")
         return
   #数据写入部分
      Value=self.ui.spin_Int8.value()
      self.fileStream.writeInt8(Value)    #int8

      Value=self.ui.spin_UInt8.value()
      self.fileStream.writeUInt8(Value)   #uint8

      Value=self.ui.spin_Int16.value()
      self.fileStream.writeInt16(Value)   #int16

      Value=self.ui.spin_UInt16.value()
      self.fileStream.writeUInt16(Value)  #uint16

      Value=self.ui.spin_Int32.value()
      self.fileStream.writeInt32(Value)   #int32

      Value=self.ui.spin_Int64.value()
      self.fileStream.writeInt64(Value)   #int64

      Value=self.ui.spin_Int.value()
      self.fileStream.writeInt(Value)     #int

      Value=self.ui.chkBox_In.isChecked()
      self.fileStream.writeBool(Value)    #bool

      Value=self.ui.spin_Float.value()
      self.fileStream.writeFloat(Value)   #float

      Value=self.ui.spin_Double.value() 
      self.fileStream.writeDouble(Value)  #double

      str_Value=self.ui.editQStr_In.text()
      self.fileStream.writeQString(str_Value)   #QString
      
      str_Value=self.ui.editStr_In.text()       #str类型
      bts=bytes(str_Value,encoding="utf-8")     #转换为bytes类型
      self.fileStream.writeString(bts)    

      font=self.ui.btnFont_In.font()
      self.fileStream.writeQVariant(font)    #QFont

      plet=self.ui.btnColor_In.palette()
      color=plet.buttonText().color() 
      self.fileStream.writeQVariant(color)   #QColor

   #数据写入完成
      self.__delFileStream()
      QMessageBox.information(self,"消息","数据连续写入完成.")


   @pyqtSlot()    ##连续读取文件
   def on_actReadALL_triggered(self):  
      if not self.__iniRead():
         QMessageBox.critical(self,"错误","为读取打开文件时出错")
         return
      
   #数据读取部分
      Value=self.fileStream.readInt8()    #int8
      self.ui.edit_Int8.setText("%d"%Value)

      Value=self.fileStream.readUInt8()   #uint8
      self.ui.edit_UInt8.setText("%d"%Value)

      Value=self.fileStream.readInt16()   #int16
      self.ui.edit_Int16.setText("%d"%Value)

      Value=self.fileStream.readUInt16()  #uint16
      self.ui.edit_UInt16.setText("%d"%Value)

      Value=self.fileStream.readInt32()   #int32
      self.ui.edit_Int32.setText("%d"%Value)

      Value=self.fileStream.readInt64()   #int64
      self.ui.edit_Int64.setText("%d"%Value)

      Value=self.fileStream.readInt()     #int
      self.ui.edit_Int.setText("%d"%Value)

      Value=self.fileStream.readBool()    #bool
      self.ui.chkBox_Out.setChecked(Value)

      Value=self.fileStream.readFloat()   #float
      self.ui.edit_Float.setText("%.4f"%Value)

      Value=self.fileStream.readDouble()  #double
      self.ui.edit_Double.setText("%.4f"%Value)

      str_Value=self.fileStream.readQString()  #str
      self.ui.editQStr_Out.setText(str_Value)

      byteStr=self.fileStream.readString()   #bytes
      str_Value=byteStr.decode("utf-8")      #从bytes类型解码为字符串
      self.ui.editStr_Out.setText(str_Value)

      font=self.fileStream.readQVariant()    #QFont
      self.ui.editFont_Out.setFont(font)

      color=self.fileStream.readQVariant()   #QColor
      plet=self.ui.editColor_Out.palette() 
      plet.setColor(QPalette.Text,color)
      self.ui.editColor_Out.setPalette(plet)
      
   #数据写入完成
      self.__delFileStream()
      QMessageBox.information(self,"消息","数据连续读取完成.")