def recv_packet(soc: socket.socket) -> bytes: global intermediary_data if len(intermediary_data.splitlines()) > 1: grams = intermediary_data.splitlines() intermediary_data = grams[1:] return grams[0] else: result = intermediary_data grams = soc.recv(1024) while '\n'.encode('utf-8') not in grams: result += grams grams = soc.recv(1024) loc = grams.find('\n'.encode('utf-8')) if loc >= 0: result += grams[:loc] if loc < len(grams) - 1: intermediary_data = grams[loc + 1:] else: intermediary_data = ''.encode('utf-8') print_notification('Received {} bytes'.format(len(result))) return result
def handle(self): """Handles the requests made by the clients""" print_notification("Handling request from {}".format(self.client_address[0])) raw = self.rfile.readline() print_info("Raw data is: {}".format(raw)) command = json.loads(raw) print_notification("Received packet containing {}".format(command)) self.wfile.write(bytes(json.dumps({'message': 'Thank you', 'frame': np.zeros(shape=(25, 40), dtype=int).tolist()}) + '\n', 'utf-8'))
import socketserver as ss from web_socket_util import get_local_ip, TCPDatagramHandler from display_util import print_notification if __name__ == "__main__": host, _ = get_local_ip() with ss.TCPServer((host, 0), TCPDatagramHandler) as server: port = server.socket.getsockname()[1] print_notification("Beginning server on port {}".format(port)) server.serve_forever()
while '\n'.encode('utf-8') not in grams: result += grams grams = soc.recv(1024) loc = grams.find('\n'.encode('utf-8')) if loc >= 0: result += grams[:loc] if loc < len(grams) - 1: intermediary_data = grams[loc + 1:] else: intermediary_data = ''.encode('utf-8') print_notification('Received {} bytes'.format(len(result))) return result if __name__ == "__main__": print_notification("Starting depth camera server client") hostname, _ = get_local_ip() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((hostname, int(get_input('Port Number? ')))) while True: sock.send( bytes( json.dumps( {'message': get_input('What would you like to say? ') }), 'utf-8') + bytes('\n', 'utf-8')) received = str(recv_packet(sock)) print_info("Received data: {}".format(received))