#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 26 17:50:16 2020 @author: suwako """ import sys, pygame, time, random, socket from colorama import Fore, Style import numpy as np import gzip import json import multiprocessing def debug(*s): print("[D ] : " + str(', '.join(map(str, s))) + Style.RESET_ALL) def info(*s): print(Fore.GREEN + Fore.LIGHTGREEN_EX + "[I -] : " + Style.RESET_ALL + str(', '.join(map(str, s))) + Style.RESET_ALL) def warn(*s): print(Fore.MAGENTA + "[W ~] : " + Style.RESET_ALL + str(', '.join(map(str, s))) + Style.RESET_ALL) def error(*s): print(Fore.RED + Fore.LIGHTRED_EX + "[E !] : " + Style.RESET_ALL + str(', '.join(map(str, s))) + Style.RESET_ALL) level = 0 BUFFER_SIZE = 4096 CONTINUE = b'\x00' END = b'\xFF' for i in range(level): exec("debug info warn error".split()[i] + "= lambda *x: None") def lookahead(iterable): it = iter(iterable) last = next(it) for val in it: yield last, CONTINUE last = val yield last, END def chunked(size, source): for i in range(0, len(source), size): yield source[i:i+size] def handle(conn, queues): try: data = bytes() while True: in_data = conn.recv(BUFFER_SIZE) if in_data == b"": info("Socket closed remotely") break if in_data[0] == CONTINUE[0]: data += in_data[1:] elif in_data[0] == END[0]: decompressed = gzip.decompress(data+in_data[1:]).decode('utf8') queues['in'].put(json.loads(decompressed)) else : warn("Invalid chunk received !!") send(conn, {'error':True, 'content':"INV_CHUNK"}) break finally: info("Closing socket") conn.close() def send(conn, data_obj): data = gzip.compress(bytes(json.dumps(data_obj), encoding='utf8')) for chunk, info in lookahead(chunked(BUFFER_SIZE - 1, data)): conn.sendall(info + chunk.ljust(BUFFER_SIZE - 1, b'\x00')) class Client(object): def __init__(self, hostname, port): self.hostname = hostname self.port = port self.queues = {'in':multiprocessing.Queue(), 'out':multiprocessing.Queue()} def start(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: info(f"Connecting to {self.hostname}:{self.port}.") self.socket.connect((self.hostname, self.port)) self.handler = multiprocessing.Process(target=handle, args=(self.socket, self.queues)) self.handler.start() send(self.socket, {'type':'Hello', 'content':{'player_name':"Suwako"}}) self.handler.join() finally: info("Exiting.") self.socket.close() if __name__ == "__main__": client = Client("localhost", 9001) client.start()