def dispatch(self, polling_mode): """Dispatch messages with the peer (read and write packets)""" event = None event_type = 1000 while event_type not in [enet.EVENT_TYPE_RECEIVE]: wait_time = 1000 if polling_mode: wait_time = 0 event = self._host.service(wait_time) event_type = event.type if event.type == enet.EVENT_TYPE_NONE: if polling_mode: return None if event.type == enet.EVENT_TYPE_RECEIVE: try: return json.loads(event.packet.data) except json.JSONDecodeError: # This happens at the end of a game for some reason? if len(event.packet.data) == 0: event_type = 0 continue return None elif event.type == enet.EVENT_TYPE_CONNECT: handshake = json.dumps({ "type": "connect_request", "cursor": 0, }) self._peer.send(0, enet.Packet(handshake.encode())) elif event.type == enet.EVENT_TYPE_DISCONNECT: return None return None
def main(): host = enet.Host(None, 1, 0, 0) peer = host.connect(enet.Address(sys.argv[1], 13000), 1) data = hashlib.md5(sys.argv[1] + 'R0Ot14').hexdigest() tries = 0 while True: evt = host.service(100) if evt.type == enet.EVENT_TYPE_NONE: tries += 1 if tries > 10: send_hint(sys.argv[1]) done(STATUS_NOT_OK, "Timeout", "Timeout") elif evt.type == enet.EVENT_TYPE_CONNECT: peer.send(0, enet.Packet(data)) elif evt.type == enet.EVENT_TYPE_RECEIVE: r_data = evt.packet.data peer.disconnect() if r_data == data: done(STATUS_OK) fail("received '%s' but '%s' expected" % (r_data, data)) else: fail("invalid event type: '%s'" % evt.type)
def send_contained(self, contained, unsequenced=False, sender=None, team=None, save=False, rule=None): if unsequenced: flags = enet.PACKET_FLAG_UNSEQUENCED else: flags = enet.PACKET_FLAG_RELIABLE writer = ByteWriter() contained.write(writer) data = bytes(writer) packet = enet.Packet(data, flags) for player in self.connections.values(): if player is sender or player.player_id is None: continue if team is not None and player.team is not team: continue if rule is not None and rule(player) == False: continue if player.saved_loaders is not None: if save: player.saved_loaders.append(data) else: player.peer.send(0, packet)
def connect(self): """ Connect to the server Returns True on success, False on failure """ # Try to connect to the server and send a handshake try: self._peer = self._host.connect( enet.Address(bytes(self.address, 'utf-8'), int(self.port)), 1) except OSError: #this should mean that we're already connected pass #shouldn't happen unless something is wrong try: event = None attempts = 0 maxAttempts = 4 #only attempt to connect 4 times while True: event = self._host.service(1000) if event.type == enet.EVENT_TYPE_CONNECT: #this means we've connected break attempts = attempts + 1 if attempts > maxAttempts: return False handshake = json.dumps({ "type": "connect_request", "cursor": 0, }) self._peer.send(0, enet.Packet(handshake.encode())) return True except OSError: #shouldn't happen unless something is wrong return False
def update(self): packets = {} # Maps client_id sender to packet for i in range(100): event = self.host.service(0) if event.type == enet.EVENT_TYPE_NONE: break client_id = str(event.peer.address) if event.type == enet.EVENT_TYPE_CONNECT: print("Client " + str(client_id) + " connected from " + str(event.peer.address)) # Send client ID event.peer.send( 0, enet.Packet(pickle.dumps(client_id), enet.PACKET_FLAG_RELIABLE)) # Handle connection self.peers[client_id] = event.peer for handler in self.handlers: handler.on_connect(client_id) self.next_client_id += 1 elif event.type == enet.EVENT_TYPE_DISCONNECT: print("Client " + str(client_id) + " has disconnected.") for handler in self.handlers: handler.on_disconnect(client_id) elif event.type == enet.EVENT_TYPE_RECEIVE: if client_id in packets: packets[client_id].append(Packet(event.packet.data)) else: packets[client_id] = [Packet(event.packet.data)] for handler in self.handlers: handler.handle_packet(Packet(event.packet.data), client_id) return packets
def send(self, data, channel=0, reliable=True, unsequenced=False): flags = 0 if reliable: flags |= enet.PACKET_FLAG_RELIABLE if unsequenced: flags |= enet.PACKET_FLAG_UNSEQUENCED self.peer.send(channel, enet.Packet(data, flags))
def sendToAll(self, data, channel=0, reliable=True, unsequenced=False): assert isinstance(data, str) flag = 0 if reliable: flag = enet.PACKET_FLAG_RELIABLE if unsequenced: flag = enet.PACKET_FLAG_UNSEQUENCED self.host.broadcast(channel, enet.Packet(data, flag))
def main(): host = enet.Host(enet.Address(b'0.0.0.0', 13000), 100, 0, 0) while True: evt = host.service(0) if evt.type == enet.EVENT_TYPE_RECEIVE: data = evt.packet.data print "%s -> '%r'" % (evt.peer.address, data) if evt.peer.send(0, enet.Packet(data)) < 0: print >> sys.stderr, "send error"
def sendData(self): if self.clientId != None: s = self.players[self.clientId] msg = pickle.dumps({ 'action': 'player_update', 'clientId': str(self.clientId), 'state': s.formatPacket() }) packet = enet.Packet(msg, 3) self.peer.send(0, packet)
def send_contained(self, contained, sequence=False): if self.disconnected: return if sequence: flags = enet.PACKET_FLAG_UNSEQUENCED else: flags = enet.PACKET_FLAG_RELIABLE data = ByteWriter() contained.write(data) packet = enet.Packet(str(data), flags) self.peer.send(0, packet)
def sendData(self): for i, s in self.players.iteritems(): msg = pickle.dumps({ 'action': 'player_update', 'clientId': str(i), 'state': s.formatPacket() }) packet = enet.Packet(msg, 3) #Odeslani vsech klientskych stavovych promennych vsem klientum. self.host.broadcast(0, packet) msg = pickle.dumps({ 'action': 'game_update', 'time': self.localTime, 'state': self.gameState.formatPacket() }) packet = enet.Packet(msg, 3) #Odeslani serverovych stavovych promennych vsem klientum. self.host.broadcast(0, packet)
def shutdown(self): """ Close down the socket and connection to the console """ if self._peer: self._peer.send(0, enet.Packet()) self._host.service(100) self._peer.disconnect() self._peer = None if self._host: self._host = None return False
def game_ready(game_name): player_count = games[game_name]['player_count'] team_count = games[game_name]['team_count'] if len(games[game_name]['game_instances']) == team_count * (player_count - 1): logger = logging.getLogger(game_name) logger.info("Game Ready.") for i, pl in enumerate(games[game_name]['game_instances']): pl.send( 0, enet.Packet( struct.pack("<I I I I 8s", i * player_count, i, player_count, team_count, '_READY_\x00'), enet.PACKET_FLAG_RELIABLE))
def test_broadcast(self): broadcast_done = False broadcast_msg = b"foo\0bar\n baz!" while not broadcast_done: event = self.client.service(0) if event.type == enet.EVENT_TYPE_RECEIVE: self.assertEquals(event.peer.state, enet.PEER_STATE_CONNECTED) self.assertEquals(event.packet.data, broadcast_msg) broadcast_done = True event = self.server.service(0) if event.type == enet.EVENT_TYPE_CONNECT: self.assertEquals(event.peer.state, enet.PEER_STATE_CONNECTED) self.server.broadcast(0, enet.Packet(broadcast_msg))
def players_connected(game_name): player_count = games[game_name]['player_count'] team_count = games[game_name]['team_count'] total_players = player_count * team_count if ((len(games[game_name]['seeders']) == total_players and len(games[game_name]['leechers']) == total_players) or (len(games[game_name]['seeders']) == total_players and games[game_name]['team_count'] == 1)): logger = logging.getLogger(game_name) logger.info("Players connected.") for pl in games[game_name]['game_instances']: pl.send( 0, enet.Packet('_PLAYERS_CONNECTED_\x00', enet.PACKET_FLAG_RELIABLE)) games[game_name]['started'] = True
def test_send(self): msg = b"foo\0bar" msg_received = False while not msg_received: event = self.server.service(0) if event.type == enet.EVENT_TYPE_RECEIVE: msg_received = True self.assertEquals(event.packet.data, msg) event = self.client.service(0) if event.type == enet.EVENT_TYPE_CONNECT: packet = enet.Packet(msg) self.assertEquals(packet.sent, False) ret = self.peer.send(0, packet) self.assertEquals(ret, 0) self.assertEquals(packet.sent, True)
def broadcast_contained(self, contained, unsequenced=False, sender=None, team=None, save=False, rule=None): """send a Contained `Loader` to all or a selection of connected players Parameters: contained: the `Loader` object to send unsequenced: set the enet ``UNSEQUENCED`` flag on this packet sender: if set to a connection object, do not send this packet to that player, as they are the sender. team: if set to a team, only send the packet to that team save: if the player has not downloaded the map yet, save this packet and send it when the map transfer has completed rule: if set to a callable, this function is called with the player as parameter to determine if a given player should receive the packet """ if unsequenced: flags = enet.PACKET_FLAG_UNSEQUENCED else: flags = enet.PACKET_FLAG_RELIABLE writer = ByteWriter() contained.write(writer) data = bytes(writer) packet = enet.Packet(data, flags) for player in self.connections.values(): if player is sender or player.player_id is None: continue if team is not None and player.team is not team: continue if rule is not None and not rule(player): continue if player.saved_loaders is not None: if save: player.saved_loaders.append(data) else: player.peer.send(0, packet)
def send_map(self, data=None): if data is not None: self.map_data = data map_start.size = data.get_size() self.send_contained(map_start) elif self.map_data is None: return if not self.map_data.data_left(): self.map_data = None for data in self.saved_loaders: packet = enet.Packet(bytes(data), enet.PACKET_FLAG_RELIABLE) self.peer.send(0, packet) self.saved_loaders = None self.on_join() return for _ in range(10): if not self.map_data.data_left(): break map_data.data = self.map_data.read(8192) self.send_contained(map_data)
def send_map(self, data: Optional[ProgressiveMapGenerator] = None) -> None: if data is not None: self.map_data = data map_start.size = data.get_size() self.send_contained(map_start) elif self.map_data is None: return if not self.map_data.data_left(): log.debug("done sending map data to {player}", player=self) self.map_data = None for data in self.saved_loaders: packet = enet.Packet(bytes(data), enet.PACKET_FLAG_RELIABLE) self.peer.send(0, packet) self.saved_loaders = None self.on_join() return for _ in range(10): if not self.map_data.data_left(): break map_data.data = self.map_data.read(8192) self.send_contained(map_data)
def connect(self): """ Connect to the server Returns True on success, False on failure """ # Try to connect to the server and send a handshake try: self._peer = self._host.connect(enet.Address(bytes(self.address, 'utf-8'), int(self.port)), 1) except OSError: return False try: for _ in range(4): event = self._host.service(1000) if event.type == enet.EVENT_TYPE_CONNECT: handshake = json.dumps({ "type" : "connect_request", "cursor" : 0, }) self._peer.send(0, enet.Packet(handshake.encode())) return True return False except OSError: return False
def _send_data(self, data, channel=0, flags=enet.PACKET_FLAG_RELIABLE, **kwargs): self.peer.send(channel, enet.Packet(data, flags))
'started': False } else: games[game_name]['game_instances'].append(e.peer) game_ready(game_name) # -- seed game elif t == AW_cmd_type_seed_game: t, game_name, player_id = struct.unpack_from( "<I 64s I", e.packet.data) game_name = game_name[:game_name.index('\x00') + 1] port = free_ports.pop() seeder = (enet.Host(enet.Address(None, port), 32, 1, 0, 0), games[game_name]['leechers'], player_id, game_name) games[game_name]['seeders'].append(seeder) packet = enet.Packet(struct.pack("<I I", port, player_id), enet.PACKET_FLAG_RELIABLE) e.peer.send(0, packet) logging.info("Seeder linked.") players_connected(game_name) # -- leech game elif t == AW_cmd_type_leech_game: t, game_name, player_id = struct.unpack_from( "<I 64s I", e.packet.data) game_name = game_name[:game_name.index('\x00') + 1] games[game_name]['leechers'].append((e.peer, player_id)) logging.info("Leecher linked.") #logging.info(games[game_name]) players_connected(game_name) else: logger.info("message type unknown")
if self.data[0] == 15: # state data self.playerid = self.data[1] import enet from time import time host = enet.Host(enet.Address(bytes('0.0.0.0', 'utf-8'), args.port), 128, 1) host.compress_with_range_coder() clients = {} client_id = 0 while True: for cl in list(clients.values()): if cl.pause_time > 0: continue if cl.spam_time is not None and cl.spam_time <= time(): pkt = struct.pack("bbb", 17, 35, 2) + str(cl.timedelta).encode('cp437', 'replace') #chat message cl.peer.send(0, enet.Packet(pkt, enet.PACKET_FLAG_RELIABLE)) cl.spam_time = time() + 1 while cl.start_time + cl.timedelta <= time(): if cl.data[0] == 3: #input data player, data = struct.unpack("xbb", cl.data) cl.playerinfo[player][0] = data elif cl.data[0] == 4: #weapon data player, data = struct.unpack("xbb", cl.data) cl.playerinfo[player][1] = data cl.peer.send(0, enet.Packet(cl.data, enet.PACKET_FLAG_RELIABLE)) try: cl.get_next_packet() except EOFError: print(cl.peer.data, "finished playback") cl.peer.disconnect(0) #ERROR_UNDEFINED cl.fh.close()
def test_dataLength(self): self.assertEquals(enet.Packet(b"foobar").dataLength, 6) self.assertEquals(enet.Packet(b"foo\0bar").dataLength, 7) self.assertRaises(MemoryError, getattr, enet.Packet(), "dataLength")
def test_flags(self): self.assertEquals(enet.Packet(b"foobar").flags, 0) self.assertEquals(enet.Packet(b"foobar", enet.PACKET_FLAG_UNSEQUENCED).flags, enet.PACKET_FLAG_UNSEQUENCED) self.assertRaises(MemoryError, getattr, enet.Packet(), "flags")
def send(self, data_string, reliable=True): if reliable: flag = enet.PACKET_FLAG_RELIABLE else: flag = None self.enetHost.broadcast(0, enet.Packet(data_string, flag))
def test_data(self): self.assertEquals(enet.Packet(b"foo\0bar").data, b"foo\0bar") self.assertRaises(MemoryError, getattr, enet.Packet(), "data")
def send(self, channel, data, reliable, no_allocate=False): flags = 0 if reliable: flags |= enet.PACKET_FLAG_RELIABLE if no_allocate: flags |= enet.PACKET_FLAG_NO_ALLOCATE packet = enet.Packet(data, flags) return self._enet_peer.send(channel, packet)
import enet SHUTDOWN_MSG = "SHUTDOWN" host = enet.Host(enet.Address(b"localhost", 54301), 10, 0, 0, 0) connect_count = 0 run = True shutdown_recv = False while run: # Wait 1 second for an event event = host.service(1000) if event.type == enet.EVENT_TYPE_CONNECT: print("%s: CONNECT" % event.peer.address) connect_count += 1 elif event.type == enet.EVENT_TYPE_DISCONNECT: print("%s: DISCONNECT" % event.peer.address) connect_count -= 1 if connect_count <= 0 and shutdown_recv: run = False elif event.type == enet.EVENT_TYPE_RECEIVE: print("%s: IN: %r" % (event.peer.address, event.packet.data)) msg = event.packet.data if event.peer.send(0, enet.Packet(msg)) < 0: print("%s: Error sending echo packet!" % event.peer.address) else: print("%s: OUT: %r" % (event.peer.address, msg)) if event.packet.data == "SHUTDOWN": shutdown_recv = True
def send(me, msg): if me.connected == False: return pack = enet.Packet(msg, enet.PACKET_FLAG_RELIABLE) me.peer.send(0, pack)