Exemplo n.º 1
0
def clientthread(conn, addr, userID):
    # sends a message to the client whose user object is conn
    welcome_msg = "Welcome to the chatroom!"
    conn.send(welcome_msg.encode())
    flag = -1
    clientFlags.append(0)
    while True:
        try:
            message = conn.recv(2048)  # buffer size 2048 bytes
            if message:

                if "CLIENTREQUESTID" in message.decode(
                ):  #[0:14 are message, [15] is id (client A's i val)
                    flag = int(message.decode()[15])
                    clientFlags[flag] = 1
                    #print("CLIENT B FLAG = " + flag) # does not print for some reason
                elif "END_NOTIF" in message.decode():
                    clientFlags[flag] = 0
                    flag = -1
                #User should type in "End Chat" to close the connection
                elif "End Chat" in message.decode():
                    conn.send("END_NOTIF".encode())
                    list_of_clients[int(flag)].send("END_NOTIF".encode())
                    clientFlags[flag] = 0
                    flag = -1

                # client A requests a chat with client B
                elif "Chat" in message.decode():
                    flag = chat_rcvd(message.decode()[5:-1], conn,
                                     userID)  #send requested client and socket
                else:
                    print("<" + userID + "> " + message.decode())
                    message_to_send = "<" + userID + "> " + message.decode()
                    # prints the message and address of the user who just sent the message on the server terminal
                    # broadcast(message_to_send[:-1],conn)
                    if flag != -1:
                        print(flag)
                        list_of_clients[int(flag)].send(
                            ("<" + userID + "> " + message.decode()).encode())
                        #conn.send(message.encode())
            else:
                remove(conn)
        except:
            continue
Exemplo n.º 2
0
    def send_query_and_get_error(self, querier):


        ping_msg = message.OutgoingPingQuery()
        query = querier.send_query(ping_msg, tc.EXTERNAL_NODE,
                                   self.on_response,
                                   self.on_timeout, self.on_error,
                                   timeout_delay=tc.TIMEOUT_DELAY)
        if querier is self.querier_mock:
            # the server creates the response
            error_msg = message.OutgoingErrorMsg(ping_msg.tid,
                                                 message.GENERIC_E)
            error_data = error_msg.encode()
            # rpc_m decodes the response received
            _, _, error_msg_dict = message.decode(error_data)
            # rpc_m notifies of the message (callback)
            querier.on_error_received(error_msg_dict, tc.EXTERNAL_NODE)
        time.sleep(tc.TIMEOUT_DELAY + .1)
Exemplo n.º 3
0
    def send_query_and_get_error(self, querier):


        ping_msg = message.OutgoingPingQuery()
        query = querier.send_query(ping_msg, tc.EXTERNAL_NODE,
                                   self.on_response,
                                   self.on_timeout, self.on_error,
                                   timeout_delay=tc.TIMEOUT_DELAY)
        if querier is self.querier_mock:
            # the server creates the response
            error_msg = message.OutgoingErrorMsg(ping_msg.tid,
                                                 message.GENERIC_E)
            error_data = error_msg.encode()
            # rpc_m decodes the response received
            _, _, error_msg_dict = message.decode(error_data)
            # rpc_m notifies of the message (callback)
            querier.on_error_received(error_msg_dict, tc.EXTERNAL_NODE)
        time.sleep(tc.TIMEOUT_DELAY + .1)
Exemplo n.º 4
0
    def command_response(self, command, timeout=None):
        """Send a command (optionally) over USB and wait for a response to come back.
        The input command is a message object and any response shall be
        first decoded to a response message object.
        """

        #FIXME: implement timeout

        if command:
            resp = self._ble.write(command.pack())

        resp = self._ble.read(timeout)

        if resp == None:
            return resp

        else:
            (msg, _) = message.decode(array('B', resp))
            return msg
Exemplo n.º 5
0
    def _request(self, obj):
        if not self.is_connected():
            raise self.APIError('Not connected to BESS daemon')

        if self.debug:
            print >> sys.stderr, '\t---> %s' % repr(obj)

        try:
            q = message.encode(obj)
        except:
            print >> sys.stderr, 'Encoding error, object: %s' % repr(obj)
            raise

        self.s.sendall(struct.pack('<L', len(q)))
        self.s.sendall(q)

        total, = struct.unpack('<L', self.s.recv(4))
        buf = []
        received = 0
        while received < total:
            frag = self.s.recv(total - received)
            buf.append(frag)
            received += len(frag)

        try:
            obj = message.decode(''.join(buf))
        except:
            print >> sys.stderr, 'Decoding error, binary: %s' % obj.encode(
                'hex')
            raise

        if self.debug:
            print >> sys.stderr, '\t<--- %s' % repr(obj)

        if isinstance(obj, dict) and 'err' in obj:
            err = obj['err']
            errmsg = obj.get('errmsg', '(error message is not given)')
            details = obj.get('details', None)
            raise self.Error(err, errmsg, details)

        return obj
Exemplo n.º 6
0
    def _request(self, obj):
        if not self.is_connected():
            raise self.APIError('Not connected to BESS daemon')

        if self.debug:
            print >> sys.stderr, '\t---> %s' % repr(obj)

        try:
            q = message.encode(obj)
        except:
            print >> sys.stderr, 'Encoding error, object: %s' % repr(obj)
            raise

        self.s.sendall(struct.pack('<L', len(q)))
        self.s.sendall(q)

        total, = struct.unpack('<L', self.s.recv(4))
        buf = []
        received = 0
        while received < total:
            frag = self.s.recv(total - received)
            buf.append(frag)
            received += len(frag)

        try:
            obj = message.decode(''.join(buf))
        except:
            print >> sys.stderr, 'Decoding error, binary: %s' % obj.encode('hex')
            raise

        if self.debug:
            print >> sys.stderr, '\t<--- %s' % repr(obj)

        if isinstance(obj, dict) and 'err' in obj:
            err = obj['err']
            errmsg = obj.get('errmsg', '(error message is not given)')
            details = obj.get('details', None)
            raise self.Error(err, errmsg, details)

        return obj
Exemplo n.º 7
0
 def read(self):
     while self.socket is not None and '\n' not in self.buffer:
         self.socket.settimeout(READ_TIMEOUT)
         try:
             input = self.socket.recv(BUFFER_SIZE)
         except socket.timeout:
             return None
         if len(input) == 0:
             self.close()
             break
         #print 'received "%s"' % input
         self.buffer = self.buffer + input.replace('\r\n', '\n')
     
     if '\n' in self.buffer:
         line,self.buffer = self.buffer.split('\n', 1)
     else:
         warn('No CRLF in buffer')
         line = self.buffer
     
     message = decode(line)
     notice('In: %s' % message)
     return message
Exemplo n.º 8
0
    def command_response(self, command, timeout=None):
        """Send a command (optionally) over USB and wait for a response to come back.
        The input command is a message object and any response shall be
        first decoded to a response message object.
        """

        if timeout != None:
            timeout = timeout * 1000  # Scale timeout to milliseconds
            timeout = int(timeout)

        if command:
            resp = self._usb.write(pyusb.EP_MSG_OUT, command.pack(), timeout)
            resp.wait()
            if resp.status == -1:
                return None
        # All command responses are guaranteed to fit inside 512 bytes
        resp = self._usb.read(pyusb.EP_MSG_IN, 512, timeout)
        resp.wait()
        if resp.status == -1:
            return None
        else:
            (msg, _) = message.decode(resp.buffer)
            return msg
Exemplo n.º 9
0
 def get(self, json):
     global game_manager
     client = game_manager.clients[self.get_current_user()]
     client.send_messages([message.decode(m) for m in escape.json_decode(escape.url_unescape(json))])