Exemplo n.º 1
0
        public void Start()
        {
            Console.WriteLine("GAME SERVER STARTED");
            EventBasedNetListener listener = new EventBasedNetListener();
            NetManager            server   = new NetManager(listener);

            server.Start(9050 /* port */);

            _netSerializer.Register <WelcomePacket>();
            _netSerializer.Register <UpdatePacket>();
            _netSerializer.Register <ServerSnapshotPacket>();
            _netSerializer.Register <EchoPacket>();

            _packetProcessor.SubscribeReusable <UpdatePacket, NetPeer>(HandleClientUpdate);



            listener.ConnectionRequestEvent += request =>
            {
                //we will change this when we create 'game sessions' for now we only support the 4 players.
                if (server.PeersCount < 4 /* max connections */)
                {
                    request.AcceptIfKey("SomeConnectionKey");
                }
                else
                {
                    request.Reject();
                }
            };

            listener.PeerConnectedEvent += peer =>
            {
                //server stores by ipaddress+port
                string key = peer.EndPoint.ToString();
                if (!_knownPlayers.ContainsKey(key))
                {
                    // new unknown player connected, let's start tracking them
                    ServerPlayerData pd = new ServerPlayerData
                    {
                        //generate a unique ID for the peer connecting which will be referenced in the future (by other peers as an intermediary (vs telling peers specifically who they're connected to IP/POrt or whatever)
                        // let's condense this down by 1/3 or so..  (also we know the final characters are ==
                        ClientID      = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Replace("=", ""),
                        GameSessionId = string.Empty,
                        IPAddress     = peer.EndPoint.Address,
                        Port          = peer.EndPoint.Port,
                        MillisecondsSinceLastHeard = 0,
                        PlayerNumber   = GetNextPlayerId() + 1,
                        PlayerLocation = new Loc {
                            X = 0, Y = 0
                        },
                        _clientRef = peer
                    };
                    bool success = _knownPlayers.TryAdd(key, pd);
                    pd.PlayerLocation.X = pd.PlayerNumber * 15;
                    pd.PlayerLocation.Y = pd.PlayerNumber * 15;
                }
                else
                {
                    //player must have disconnected during a game, let's try to reconnect to their game if it's still playing
                    //TODO: look up the GameSessionID, then start sending this player's packets to all players in the session
                }


                var pdat = _knownPlayers[key];
                Console.WriteLine("PLAYER JOINED: {0} as PLAYER {1} with ID {2}", peer.EndPoint, pdat.PlayerNumber, pdat.ClientID);
                //send our info in a welcome packet
                WelcomePacket wp = new WelcomePacket
                {
                    PlayerId     = pdat.ClientID,
                    PlayerNumber = pdat.PlayerNumber,
                    XStart       = pdat.PlayerLocation.X,
                    YStart       = pdat.PlayerLocation.Y
                };

                _packetProcessor.Send <WelcomePacket>(peer, wp, DeliveryMethod.ReliableOrdered);
                Console.WriteLine("Packet Processor Sent Packet!");
                //peer.Send(_netSerializer.Serialize<WelcomePacket>(wp), DeliveryMethod.ReliableOrdered);
            };

            listener.NetworkReceiveEvent += Listener_NetworkReceiveEvent;

            while (!Console.KeyAvailable)
            {
                server.PollEvents();
                UpdateAllClients(); //sends a snapshot of all client locations every 15ms
                Thread.Sleep(15);
            }
            server.Stop();
        }