def _handle_outgoing(self, writable): for s in writable: wrapped_socket = SocketWrapper(s) try: next_msg = self._message_queues[s].get_nowait() except queue.Empty: logger.debug('output queue for {} is empty'.format((s.getpeername()))) self._outgoing_connections.remove(s) else: logger.debug('sending "%s" to %s' % (next_msg, s.getpeername())) wrapped_socket.send(next_msg)
def connect(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sock.connect(self.server_address()) self._wrapped_sock = SocketWrapper(self._sock)
class Client(): def __init__(self): self._config = configuration.Configuration() self._sock = None self._wrapped_sock = None self._board = Board() self._logger = logging.getLogger(__name__) self._finished = False self._player_sign = None def server_port(self): return int(self._config.server_port) def server_host(self): return self._config.server_ip def server_address(self): return self.server_host(), self.server_port() def connect(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sock.connect(self.server_address()) self._wrapped_sock = SocketWrapper(self._sock) def disconnect(self): self._sock.close() def join_game(self): self.send(msg.JoinGame('Hello')) def send(self, message): self._wrapped_sock.send(message) print('sending: {}'.format(message)) def receive(self): return self._wrapped_sock.recv() def _handle_response(self, data): if not data: print('Could not get response from server') s.close() sys.exit() else: if isinstance(data, msg.GameFull): print(data) self._sock.close() return elif isinstance(data, msg.PlayerSign): print(data) self._player_sign = data elif isinstance(data, msg.RefreshBoard): self._board = data.message() print('Received Board\n', self._board) elif isinstance(data, msg.GameFinish): print(data) self._finished = True elif isinstance(data, msg.IllegalMove): print(data) elif isinstance(data, msg.MoveAccepted): print(data) elif isinstance(data, msg.GameReady): print(data) elif isinstance(data, msg.GameStart): print(data) elif isinstance(data, msg.GameNotReady): print(data) def run(self): self.connect() self.join_game() socks = [self._sock, sys.stdin] while not self._finished: received, writable, exceptional = select.select(socks, [], []) for s in received: if s == self._sock: data = self.receive() self._handle_response(data) else: params = sys.stdin.readline().split() self.send(msg.MakeMove(params))