コード例 #1
0
    def run(self):
        # Try to connect to an incoming tcp socket using its socket descriptor
        tcpSocket = QTcpSocket()
        if not tcpSocket.setSocketDescriptor(self.socketDescriptor):
            FreeCAD.Console.PrintError("Socket not accepted.\n")
            return
        FreeCAD.Console.PrintLog("Socket accepted.\n")

        # Wait for an incoming message
        if not tcpSocket.waitForReadyRead(msecs=WAIT_TIME_MS):
            FreeCAD.Console.PrintError("No request send.\n")
            return

        # Make an input data stream
        instr = QDataStream(tcpSocket)
        instr.setVersion(QDataStream.Qt_4_0)

        # Try to read the message size
        if self.blockSize == 0:
            if tcpSocket.bytesAvailable() < 2:
                FreeCAD.Console.PrintError("Received message "
                                           + "has too few bytes.\n")
                return
            self.blockSize = instr.readUInt16()

        # Check message is sent complete
        if tcpSocket.bytesAvailable() < self.blockSize:
            FreeCAD.Console.PrintError("Received message has less bytes "
                                       + "then it's supposed to.\n")
            return

        # Read message and inform about it
        cmd = instr.readRawData(self.blockSize).decode("UTF-8")
        FreeCAD.Console.PrintLog("CommandServer received> "
                                 + cmd + "\n")

        # Try to execute the message string and prepare  a response
        try:
            exec(cmd)
        except Exception as e:
            FreeCAD.Console.PrintError("Executing external command failed:"
                                       + str(e) + "\n")
            message = "Command failed - " + str(e)
        else:
            FreeCAD.Console.PrintLog("Executing external command succeeded!\n")
            message = COMMAND_EXECUTED_CONFIRMATION_MESSAGE

        # Prepare the data block to send back and inform about it
        FreeCAD.Console.PrintLog("CommandServer sending> " + message + " \n")
        block = QByteArray(
                len(message.encode("UTF-8")).to_bytes(2, byteorder='big')
                + message.encode("UTF-8"))
        outstr = QDataStream(block, QIODevice.WriteOnly)
        outstr.setVersion(QDataStream.Qt_4_0)

        # Send the block, disconnect from the socket and terminate the QThread
        tcpSocket.write(block)
        tcpSocket.disconnectFromHost()
        tcpSocket.waitForDisconnected()
コード例 #2
0
    def run(self):
        # Try to connect to an incomming tcp socket using its socket descriptor
        tcpSocket = QTcpSocket()
        if not tcpSocket.setSocketDescriptor(self.socketDescriptor):
            FreeCAD.Console.PrintError("Socket not accepted.\n")
            return

        # Wait for an incomming message
        if not tcpSocket.waitForReadyRead(msecs=WAIT_TIME_MS):
            FreeCAD.Console.PrintError("No request send.\n")
            return

        # Make an input data stream
        instr = QDataStream(tcpSocket)
        instr.setVersion(QDataStream.Qt_4_0)

        # Try to read the message size
        if self.blockSize == 0:
            if tcpSocket.bytesAvailable() < 2:
                return
            self.blockSize = instr.readUInt16()

        # Check message is sent complete
        if tcpSocket.bytesAvailable() < self.blockSize:
            return

        # Read message and inform about it
        instr = instr.readString()
        FreeCAD.Console.PrintLog("CommandServer received> " + str(instr) +
                                 "\n")

        # Try to execute the message string and prepare  a response
        try:
            exec(str(instr))
        except Exception as e:
            FreeCAD.Console.PrintError("Executing external command failed:" +
                                       str(e) + "\n")
            message = "Command failed - " + str(e)
        else:
            FreeCAD.Console.PrintLog("Executing external command succeded!\n")
            message = COMMAND_EXECUTED_CONFIRMATION_MESSAGE

        # Prepare the data block to send back and inform about it
        FreeCAD.Console.PrintLog("CommandServer sending> " + message + " \n")
        block = QByteArray()
        outstr = QDataStream(block, QIODevice.WriteOnly)
        outstr.setVersion(QDataStream.Qt_4_0)
        outstr.writeUInt16(0)
        outstr.writeQString(message)
        outstr.device().seek(0)
        outstr.writeUInt16(block.size() - 2)

        # Send the block, disconnect from the socket and terminate the QThread
        tcpSocket.write(block)
        tcpSocket.disconnectFromHost()
        tcpSocket.waitForDisconnected()
コード例 #3
0
    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()
コード例 #4
0
    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()
コード例 #5
0
ファイル: corssing2.py プロジェクト: demolice/Projects
class CrossingNetwork(QObject):
    # Změna stavu; signál pro stavový řádek
    stateChanged = Signal(str)

    def __init__(self, model, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.model = model

        # Inicializace socketu
        self.socket = QTcpSocket(self)
        self.socket.readyRead.connect(self.read)
        self.socket.stateChanged.connect(self.socketStateChanged)

        # Příprava pro čtení dat
        self.readBuffer = QByteArray()
        self.textCodec = QTextCodec.codecForName("UTF-8")

    @Slot()
    def socketConnect(self):
        # Nejdřív se odpoj, pokud už spojení běží
        self.socket.abort()

        # A znovu se připoj
        self.socket.connectToHost(
            "ksp.mff.cuni.cz", 48888)

    @Slot()
    def socketDisconnect(self):
        # Odpoj se
        self.socket.disconnectFromHost()

        # Vyprázdni model
        self.model.flush()

    @Slot(SocketState)
    def socketStateChanged(self, state):
        if state == SocketState.ConnectedState:
            # Připojeni? Pozdravíme server.
            self.socket.write(self.textCodec.fromUnicode("HELLO\n"))

        # A informujeme připojené posluchače o změně stavu
        self.stateChanged.emit(str(state).split(".")[-1].split("State")[0])

    def read(self):
        # Přečteme všechno, co jsme dostali
        while self.socket.bytesAvailable() > 0:
            self.readBuffer += \
                self.socket.read(128)

        # Rozdělíme na řádky
        lines = self.readBuffer.split("\n")

        # Zbytek uložíme na příště
        self.readBuffer = lines.pop()

        # Zpracujeme řádky, které dorazily
        for l in lines:
            stripped = self.textCodec.toUnicode(l.data()).rstrip()
            args = stripped.split(" ")
            travellerType = args.pop(0)
            argmap = dict(map(
                lambda x: x.split("="), args))

            if travellerType == "CAR":
                self.addTraveller(Car(**argmap))
            elif travellerType == "PEDESTRIAN":
                self.addTraveller(
                    Pedestrian(**argmap))

    def addTraveller(self, traveller):
        # Uložíme si cestovatele
        self.model.add(traveller)

        # Nechť cestovatel vstoupí do oblasti
        traveller.start(self)

    def sendBack(self, traveller):
        # Vrátíme cestovatele serveru
        text = str(traveller) + "\n"
        self.socket.write(self.textCodec.fromUnicode(text))

        self.model.remove(traveller)
コード例 #6
0
    def run(self):
        """
Thread's functionality method.

The starting point for the thread. After calling start(), the newly created
thread calls this function. This function then tries to make QTcpSocket.
It waits `WAIT_TIME_MS` for an incoming message. If message is received
it checks its a whole message using blockSize sent in the first word as
an UINT16 number. If a whole message is received, the thread tries to execute
the message string and sends back an appropriate response. The response is
*Command failed - "error string"* if the execution failed, or *Command
executed successfully* otherwise. Then the thread is terminated.
        """
        # Try to connect to an incoming tcp socket using its socket descriptor
        tcpSocket = QTcpSocket()
        if not tcpSocket.setSocketDescriptor(self.socketDescriptor):
            FreeCAD.Console.PrintError("Socket not accepted.\n")
            return
        FreeCAD.Console.PrintLog("Socket accepted.\n")

        # Wait for an incoming message
        if not tcpSocket.waitForReadyRead(msecs=WAIT_TIME_MS):
            FreeCAD.Console.PrintError("No request send.\n")
            return

        # Make an input data stream
        instr = QDataStream(tcpSocket)
        instr.setVersion(QDataStream.Qt_4_0)

        # Try to read the message size
        if self.blockSize == 0:
            if tcpSocket.bytesAvailable() < 2:
                FreeCAD.Console.PrintError("Received message " +
                                           "has too few bytes.\n")
                return
            self.blockSize = instr.readUInt16()

        # Check message is sent complete
        if tcpSocket.bytesAvailable() < self.blockSize:
            FreeCAD.Console.PrintError("Received message has less bytes " +
                                       "then it's supposed to.\n")
            return

        # Read message and inform about it
        cmd = instr.readRawData(self.blockSize).decode("UTF-8")
        FreeCAD.Console.PrintLog("CommandServer received> " + cmd + "\n")

        # Try to execute the message string and prepare  a response
        try:
            exec(cmd)
        except Exception as e:
            FreeCAD.Console.PrintError("Executing external command failed:" +
                                       str(e) + "\n")
            message = "Command failed - " + str(e)
        else:
            FreeCAD.Console.PrintLog("Executing external command succeeded!\n")
            message = COMMAND_EXECUTED_CONFIRMATION_MESSAGE

        # Prepare the data block to send back and inform about it
        FreeCAD.Console.PrintLog("CommandServer sending> " + message + " \n")
        block = QByteArray(
            len(message.encode("UTF-8")).to_bytes(2, byteorder='big') +
            message.encode("UTF-8"))
        outstr = QDataStream(block, QIODevice.WriteOnly)
        outstr.setVersion(QDataStream.Qt_4_0)

        # Send the block, disconnect from the socket and terminate the QThread
        tcpSocket.write(block)
        tcpSocket.disconnectFromHost()
        tcpSocket.waitForDisconnected()