def setUp(self):
     self.client = enet.Host(None, 1, 0, 0, 0)
     self.server = enet.Host(enet.Address("localhost", 54301), 1, 0, 0, 0)
     self.peer = self.client.connect(enet.Address("localhost", 54301), 1)
     self.assertEquals(self.peer.state, enet.PEER_STATE_CONNECTING)
     self.assertTrue(self.peer == self.peer)
     self.assertFalse(self.peer != self.peer)
Beispiel #2
0
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)
Beispiel #3
0
 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
Beispiel #4
0
 def connect(self, connection_class, host, port, version, channel_count=1,
             timeout=5.0):
     peer = self.host.connect(enet.Address(host, port), channel_count,
                              version)
     connection = connection_class(self, peer)
     connection.timeout_call = reactor.callLater(timeout,
                                                 connection.timed_out)
     self.clients[peer] = connection
     return connection
Beispiel #5
0
    def connect(self):
        """ Connect to the server

        Returns True on success, False on failure
        """
        # Try to connect to the server and send a handshake
        self._peer = self._host.connect(
            enet.Address(bytes(self.address, 'utf-8'), int(self.port)), 1)
        return True
Beispiel #6
0
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"
Beispiel #7
0
    def __init__(self, port, max_connections):
        self.address = enet.Address(enet.HOST_ANY, port)
        self.maxConnections = max_connections
        self.host = enet.Host(self.address, max_connections, 0, 0)
        if not self.host:
            raise "Host could not be created"

        #connections stored in a dictionary, with the keys being
        #(host_string, port_number) tuple.
        self.connections = {}
Beispiel #8
0
 def __init__(self, port=None, interface=b'*', update_interval=1 / 60.0):
     if port is not None and interface is not None:
         address = enet.Address(interface, port)
     else:
         address = None
     self.host = enet.Host(address, self.max_connections, 1)
     self.host.compress_with_range_coder()
     self.update_loop = LoopingCall(self.update)
     self.update_loop.start(update_interval, False)
     self.connections = {}
     self.clients = {}
Beispiel #9
0
    def __init__(me, port, ip=None, serv=True):
        me.ok = True
        me.errs = []
        me.connected = False

        addr = enet.Address("", port) if serv else None
        print addr
        try:
            me.host = enet.Host(addr, 1, 0, 0)
        except:
            me.log(exc_info, "Unable to create host", addr)

        me.peer = None

        if serv:
            me.wait_for_connection()
        else:
            me.connect(enet.Address(ip, port))

        me.unread = deque()
Beispiel #10
0
 def _create_connection(self,
                        host,
                        port,
                        message_factory,
                        channels=1,
                        **kwargs):
     host = enet.Address(host, port)
     peer = self.host.connect(host, channels, message_factory.get_hash())
     connection = Connection(self, peer, message_factory)
     peer_id = peer.data = str(connection.id)
     return connection, peer_id
Beispiel #11
0
 def __init__(self,
              host='',
              port=0,
              conn_limit=4,
              handler=None,
              message_factory=None,
              *args,
              **kwargs):
     super(Server, self).__init__(host, port, conn_limit, handler,
                                  message_factory, *args, **kwargs)
     host = enet.Address(host, port)
     self.host = enet.Host(host, conn_limit, *args, **kwargs)
Beispiel #12
0
 def test_richcmp(self):
     self.assertTrue(
         enet.Address("127.0.0.1", 9999) == enet.Address("127.0.0.1", 9999))
     self.assertTrue(
         enet.Address("127.0.0.1", 9999) != enet.Address("127.0.0.1", 8888))
     self.assertFalse(
         enet.Address("127.1.1.1", 1992) == enet.Address("127.0.0.1", 9999))
    def listen(self, factory):
        self._factory = factory

        self._address = enet.Address(self._interface, self._port)
        enet_host = enet.Host(self._address, self._maxclients, self._channels,
                              self._maxdown, self._maxup)

        self._enet_host = ENetHost(enet_host, factory)

        self._enet_host.duplicate_peers = self._max_duplicate_peers

        log.msg("%s starting on %s" % (self._getLogPrefix(), self._port))

        self._reactor.addReader(self._enet_host)
Beispiel #14
0
    def __init__(self, port=None, interface=b'*', update_interval=1 / 60.0):
        if port is not None and interface is not None:
            address = enet.Address(interface, port)
        else:
            address = None
        try:
            self.host = enet.Host(address, self.max_connections, 1)
        except MemoryError:
            # pyenet raises memoryerror when the enet host could not be created
            raise IOError("Failed  to Create Enet Host. Is the Port in use?")

        self.host.compress_with_range_coder()
        self.update_loop = asyncio.ensure_future(self.update())
        self.connections = {}
        self.clients = {}
Beispiel #15
0
    def create(self, args):
        ap = getParam('address')
        if ap == '':
            ipAddress = '127.0.0.1'
        else:
            ipAddress = ap

        pp = getParam('port')
        if pp == '':
            port = 667
        else:
            port = pp

        self.host = enet.Host(enet.Address(ipAddress, port), 16, 0, 0, 0)
        print "Game server started ..."

        self.server = VideoServer(ipAddress)
Beispiel #16
0
    def create(self, args):

        ap = getParam('address')
        if ap == '':
            ipAddress = '127.0.0.1'
        else:
            ipAddress = ap

        pp = getParam('port')
        if pp == '':
            port = 667
        else:
            port = pp

        print self.clientConnected
        self.host = enet.Host(None, 32, 2, 0, 0)
        self.peer = self.host.connect(enet.Address(ipAddress, port), 1)
        print "Game client connecting to " + ipAddress + ":" + str(port)
        self.client = VideoClient(ipAddress)
Beispiel #17
0
    def connect(self):
        """ Connect to the server

        Returns True on success, False on failure
        """
        # If we don't have a slippi address, let's autodiscover it
        if not self.address:
            # Slippi broadcasts a UDP message on port
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # Slippi sends an advertisement every 10 seconds. So 20 should be enough
            sock.settimeout(20)
            sock.bind(('', 20582))
            try:
                message = sock.recvfrom(1024)
                self.address = message[1][0]
            except socket.timeout:
                return False

        # Try to connect to the server and send a handshake
        self._peer = self._host.connect(
            enet.Address(bytes(self.address, 'utf-8'), int(self.port)), 1)
        return True
Beispiel #18
0
    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
Beispiel #19
0
    def __init__(self, host, port):
        # Connect
        self.host = enet.Host(None, 1, 0, 0, 0)
        self.peer = self.host.connect(enet.Address(host.encode("utf-8"), port),
                                      1)

        # Wait up to 5 seconds for connection to succeed
        event = self.host.service(5000)
        if event.type == enet.EVENT_TYPE_CONNECT:
            print("Successfully connected to server.")
        else:
            raise Exception("Failed to connect to server")

        # Receive client ID from server
        event = self.host.service(1000)
        if event.type == enet.EVENT_TYPE_RECEIVE:
            self.client_id = pickle.loads(event.packet.data)
            print("Client ID is " + str(self.client_id))
        else:
            raise Exception("Failed to receive client ID from server.")

        # Other stuff
        self.handlers = []
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
Beispiel #21
0
		self.playerinfo = [[0,0] for _ in range(32)]
		self.playerid = None
	def get_next_packet(self):
		fmt = "fH"
		fmtlen = struct.calcsize(fmt)
		meta = self.fh.read(fmtlen)
		if len(meta) < fmtlen:
			raise EOFError("replay file finished")
		self.timedelta, size = struct.unpack(fmt, meta)
		self.data = self.fh.read(size)
		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
Beispiel #22
0
import enet
import random
import sys

try:
    random.seed(sys.argv[1])
except IndexError:
    pass

SHUTDOWN_MSG = b"SHUTDOWN"
MSG_NUMBER = 10

host = enet.Host(None, 1, 0, 0, 0)
peer = host.connect(enet.Address(b"localhost", 54301), 1)

counter = 0
run = True
while run:
    event = host.service(1000)
    if event.type == enet.EVENT_TYPE_CONNECT:
        print("%s: CONNECT" % event.peer.address)
    elif event.type == enet.EVENT_TYPE_DISCONNECT:
        print("%s: DISCONNECT" % event.peer.address)
        run = False
        continue
    elif event.type == enet.EVENT_TYPE_RECEIVE:
        print("%s: IN:  %r" % (event.peer.address, event.packet.data))
        continue
    msg = bytes(bytearray([random.randint(0,255) for i in range(40)]))
    packet = enet.Packet(msg)
    peer.send(0, packet)
Beispiel #23
0
 def __init__(self, port):
     self.host = enet.Host(enet.Address(None, port), 10, 0, 0, 0)
     self.peers = {}  # Map client IDs to peers
     self.handlers = []
     self.next_client_id = 1
 def test_host(self):
     self.assertEquals(enet.Address("127.0.0.1", 9999).host, "127.0.0.1")
     self.assertEquals(enet.Address("localhost", 9999).host, "127.0.0.1")
     self.assertEquals(enet.Address(None, 9999).host, "*")
     self.assertRaises(IOError, enet.Address, "foo.bar.baz.999", 9999)
Beispiel #25
0
# --
AW_cmd_type_none = 0
AW_cmd_type_unit_order = 1
AW_cmd_type_spawn_unit = 2
AW_cmd_type_build_unit = 3
AW_cmd_type_generic = 4
AW_cmd_type_end_of_turn = 5
AW_cmd_type_join_game = 6
AW_cmd_type_seed_game = 7
AW_cmd_type_leech_game = 8
AW_cmd_type_ping = 9

# --
free_ports = range(MASTER_SERVER_PORT + 1,
                   MASTER_SERVER_PORT + MASTER_SERVER_PORT_COUNT)
master_host = enet.Host(enet.Address(None, MASTER_SERVER_PORT), 32, 1, 0, 0)
games = dict()
run = True
logging.info("Running, waiting for connection...")


# --
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(
 def test_str(self):
     self.assertEquals(enet.Address("127.0.0.1", 9999).__str__(), "127.0.0.1:9999")
 def test_hostname(self):
     import socket
     self.assertEquals(enet.Address(socket.gethostname(), 9999).hostname, socket.gethostname())
     self.assertEquals(enet.Address(None, 9999).hostname, "*")
 def test_port(self):
     self.assertEquals(enet.Address("127.0.0.1", 9999).port, 9999)
     self.assertRaises(TypeError, enet.Address, "127.0.0.1", "foo")
Beispiel #29
0
import enet
host = enet.Host(None, 1, 0, 0)
peer = host.connect(enet.Address("localhost", 33333), 1)
Beispiel #30
0
 def __init__(self, addr, port, channels=2):
     self.enetHost = enet.Host(None, 1, 0, 0)
     if self.enetHost is None: raise "Could not create host"
     self.connection = None
     self.state = "connecting"
     self.enetHost.connect(enet.Address(addr, port), channels)