Example #1
0
        /// <summary>
        /// Handles when the connection info packet was recevied
        /// </summary>
        /// <param name="inMsg">The message to read</param>
        private void HandleConnectInfo(NetIncomingMessage inMsg)
        {
            myPlayerId = inMsg.ReadByte();
            isHost     = inMsg.ReadBoolean();
            inMsg.ReadPadBits();

            myConnectedServer = ServerTag.ReadFromPacket(inMsg);

            int supportedPlayers = inMsg.ReadInt32();
            int numPlayers       = inMsg.ReadByte();

            myKnownPlayers.Resize(supportedPlayers);

            for (int index = 0; index < numPlayers; index++)
            {
                Player player = new Player(0, "", false);
                player.Decode(inMsg);

                myKnownPlayers[player.PlayerId] = player;
            }

            myLocalState.Decode(inMsg);

            OnFinishedConnect?.Invoke(this, EventArgs.Empty);
        }
Example #2
0
        public static void SendDataAboutHost(ServerTag serverTag)
        {
            var client = clients[serverTag.SenderID];

            client.ClientWriter.Write((byte)NetMessageType.DataHosts);
            serverTag.WriteToPacket(client.ClientWriter, serverTag.SenderID);
        }
        private void ReceivedDataAboutHosts(object obj)
        {
            var serverTag = new ServerTag();

            serverTag.ReadFromPacket(browserReader);
            OnHostDiscovered.Invoke(serverTag);
        }
        public void ConnectTo(ServerTag host)
        {
            if (ConnectedServer == null)
            {
                SetLobbyTcp(PlayerUntill.IPAddress, host.Port);
                CheckConnection(ref lobbyWriter);

                try
                {
                    ConnectedServer = host;
                    ConnectedServer.PlayersCount = 0;
                    lobbyWriter.Write((byte)NetMessageType.ConnectionApproval);
                    ConnectedServer.WriteDataPlayer(lobbyWriter, PlayerUntill);
                }
                catch
                {
                    ConnectedServer = null;
                    MessageBox.Show("You cannot connect to this host");
                    return;
                }

                OnConnected.Invoke();
            }
            else
            {
                throw new InvalidOperationException("Cannot connect when this client is already connected");
            }
        }
Example #5
0
        private void ReadAndSendDataHost()
        {
            var serverTag = new ServerTag();

            serverTag.ReadFromPacket(hostReader);
            MainClientServer.SendDataAboutHost(serverTag);
        }
Example #6
0
        /// <summary>
        /// Invoked when a server list item has been double clicked
        /// </summary>
        /// <param name="sender">The object to be invoked</param>
        /// <param name="e">The mouse event argument containing the mouse information</param>
        private void ServerListDoubleClicked(object sender, MouseEventArgs e)
        {
            int row = dgvServers.HitTest(e.X, e.Y).RowIndex;

            if (row >= 0 && row < dgvServers.RowCount)
            {
                DataGridViewRow dataRow = dgvServers.Rows[row];

                if (dataRow != null)
                {
                    if (!myClient.IsReady)
                    {
                        myClient.Run();
                    }


                    ServerTag tag = (ServerTag)dataRow.Tag;

                    string password = "";

                    if (tag.PasswordProtected)
                    {
                        password = Prompt.ShowDialog("Enter password", "Enter Password");
                    }

                    myClient.ConnectTo(tag);
                }
            }
        }
Example #7
0
        /// <summary>
        /// Handles the serverStateUpdated packet type
        /// </summary>
        /// <param name="inMsg">The message to decode</param>
        private void HandleServerStateReceived(NetIncomingMessage inMsg)
        {
            if (myConnectedServer != null)
            {
                ServerTag tag = myConnectedServer.Value;
                tag.State         = (ServerState)inMsg.ReadByte();
                myConnectedServer = tag;

                OnServerStateUpdated?.Invoke(this, tag.State);
            }
        }
        private void UpdateHosts(ServerTag tag)
        {
            var row = new DataGridViewRow();

            row.Tag = tag;
            row.CreateCells(dgvServers);
            row.Cells[0].Value = tag.Name;
            row.Cells[1].Value = tag.PlayersCount + "/" + tag.SupportedPlayerCount;

            dgvServers.Rows.Add(row);
        }
Example #9
0
        /// <summary>
        /// Invoked when a new server has been discovered
        /// </summary>
        /// <param name="sender">The object that raised the event</param>
        /// <param name="tag">The server tag that was discovered</param>
        private void NewServerDiscovered(object sender, ServerTag tag)
        {
            DataGridViewRow row = new DataGridViewRow();

            row.Tag = tag;
            row.CreateCells(dgvServers);
            row.Cells[0].Value = tag.Name;
            row.Cells[1].Value = tag.PlayerCount + "/" + tag.SupportedPlayerCount;

            dgvServers.Rows.Add(row);
        }
Example #10
0
        /// <summary>
        /// Initializes the lobby in multiplayer mode, with the player connecting to another server
        /// </summary>
        /// <param name="tag">The tag to connect to</param>
        public void InitMultiplayer(ServerTag tag)
        {
            myServer = null;

            InitClient();

            string password = "";

            if (tag.PasswordProtected)
            {
                password = Prompt.ShowDialog("Enter password", "Enter Password");
            }

            myClient.ConnectTo(tag, password);
            btnStart.Text = "Ready";
        }
Example #11
0
        /// <summary>
        /// Initializes the lobby in multiplayer mode, with the player connecting to another server
        /// </summary>
        /// <param name="client">The client to connect with</param>
        /// <param name="tag">The tag to connect to</param>
        public void InitMultiplayer(GameClient client, ServerTag tag)
        {
            myServer = null;

            myClient = client;
            isParentControllingClient = true;

            InitClient();

            string password = "";

            if (tag.PasswordProtected)
            {
                password = Prompt.ShowDialog("Enter password", "Enter Password");
            }

            myClient.ConnectTo(tag, password);
            btnStart.Text = "Ready";
        }
Example #12
0
        /// <summary>
        /// Creates a new instance of a game server
        /// </summary>
        public GameServer(int numPlayers = 4)
        {
            myTag = new ServerTag();
            myTag.SupportedPlayerCount = numPlayers;

            myPlayRules  = new List <IGamePlayRule>();
            myStateRules = new List <IGameStateRule>();
            myInitRules  = new List <IGameInitRule>();

            myPlayers = new PlayerCollection(numPlayers);
            myBots    = new List <BotPlayer>();

            myState     = ServerState.InLobby;
            myGameState = new GameState();
            myGameState.OnStateChanged += MyGameState_OnStateChanged;

            myMessageHandlers = new Dictionary <MessageType, PacketHandler>();

            InitServer();
        }
Example #13
0
        /// <summary>
        /// Connects to a specified server
        /// </summary>
        /// <param name="server">The server tag to connect to</param>
        /// <param name="serverPassword">The SHA256 encrypted password to connect to the server</param>
        public void ConnectTo(ServerTag server, string serverPassword = "")
        {
            if (myConnectedServer == null)
            {
                // Hash the password before sending
                serverPassword = SecurityUtils.Hash(serverPassword);

                // Write the hail message and send it
                NetOutgoingMessage hailMessage = myPeer.CreateMessage();
                myTag.WriteToPacket(hailMessage);
                hailMessage.Write(serverPassword);

                // Update our connected tag
                myConnectedServer = server;

                // Attempt the connection
                myPeer.Connect(server.Address, hailMessage);
            }
            else
            {
                throw new InvalidOperationException("Cannot connect when this client is already connected");
            }
        }
Example #14
0
 /// <summary>
 /// Invoked when a client has received a discovery response from a server
 /// </summary>
 /// <param name="sender">The object that raised the event</param>
 /// <param name="tag">The server tag that was discovered</param>
 private void ServerDiscovered(object sender, ServerTag tag)
 {
     myServers.AddItem(tag);
 }
Example #15
0
 /// <summary>
 /// Invoked when a server tag has been updated
 /// </summary>
 /// <param name="sender">The object that raised the event</param>
 /// <param name="e">The server tag that was updated</param>
 private void ServerUpdated(object sender, ServerTag e)
 {
     myListItems[e].Cells[0].Value = e.Name;
     myListItems[e].Cells[1].Value = e.PlayerCount + "/" + e.SupportedPlayerCount;
 }
Example #16
0
 public virtual void WriteServerTag(ServerTag tag)
 {
     WriteToken(tag.StartToken);
     if (tag.StartToken.ServerTagClass == ServerTagClass.Declaration) { WriteToken(tag.NameToken); WriteAttributes(tag.Attributes); } else WriteToken(tag.ValueToken);
     WriteToken(tag.EndToken);
     WriteNewLineAfter(tag.NewLineAfter);
 }
Example #17
0
        /// <summary>
        /// Invoked when the network peer has received a message
        /// </summary>
        /// <param name="state">The object that invoked this (NetPeer)</param>
        private void MessageReceived(object state)
        {
            // Get the incoming message
            NetIncomingMessage inMsg = ((NetPeer)state).ReadMessage();

            // We don't want the server to crash on one bad packet
            try
            {
                // Determine the message type to correctly handle it
                switch (inMsg.MessageType)
                {
                // Handle when a client's status has changed
                case NetIncomingMessageType.StatusChanged:
                    // Gets the status and reason
                    NetConnectionStatus status = (NetConnectionStatus)inMsg.ReadByte();
                    string reason = inMsg.ReadString();

                    // Depending on the status, we handle players joining or leaving
                    switch (status)
                    {
                    case NetConnectionStatus.Disconnected:

                        // If the reason the is shutdown message, we're good
                        if (reason.Equals(NetSettings.DEFAULT_SERVER_SHUTDOWN_MESSAGE))
                        {
                            OnDisconnected?.Invoke(this, EventArgs.Empty);
                        }
                        // Otherwise if the reason is that \/ , then we timed out
                        else if (reason.Equals("Failed to establish connection - no response from remote host", StringComparison.InvariantCultureIgnoreCase))
                        {
                            OnConnectionTimedOut?.Invoke(this, EventArgs.Empty);

                            OnDisconnected?.Invoke(this, EventArgs.Empty);
                        }
                        else if (reason.StartsWith("You have been kicked:"))
                        {
                            OnKicked?.Invoke(this, reason);

                            OnDisconnected?.Invoke(this, EventArgs.Empty);
                        }
                        // Otherwise the connection failed for some other reason
                        else
                        {
                            OnDisconnected?.Invoke(this, EventArgs.Empty);
                        }

                        if (isApproving)
                        {
                            OnConnectionFailed?.Invoke(this, reason);
                        }

                        isApproving = false;

                        // Clear local state and forget connected server tag
                        myLocalState.Clear();
                        myConnectedServer = null;
                        isReady           = false;
                        isHost            = false;
                        myKnownPlayers.Clear();
                        myLocalState.Clear();
                        myHand.Clear();

                        break;

                    case NetConnectionStatus.RespondedAwaitingApproval:
                        isApproving = true;
                        break;

                    // We connected
                    case NetConnectionStatus.Connected:
                        isApproving = false;
                        // invoked the onConnected event
                        OnConnected?.Invoke(this, EventArgs.Empty);
                        break;
                    }

                    break;

                // Handle when the server has received a discovery request
                case NetIncomingMessageType.DiscoveryResponse:
                    // Read the server tag from the packet
                    ServerTag serverTag = ServerTag.ReadFromPacket(inMsg);

                    // Notify that we discovered a server
                    OnServerDiscovered?.Invoke(this, serverTag);

                    break;

                // Handles when the server has received data
                case NetIncomingMessageType.Data:
                    HandleMessage(inMsg);
                    break;
                }
            }
            // An exception has occured parsing the packet
            catch (Exception e)
            {
                //Log the exception
                Logger.Write(e);
            }
        }
Example #18
0
 public bool ParseServerTag(ServerTag tag)
 {
     tag.Clear();
     tag.NewLineAfter.Value = string.Empty;
     if (CurrentToken.Class == TokenClass.ServerTagStart) {
         var sc = CurrentToken.ServerTagClass;
         tag.StartToken.Read();
         switch (sc) {
         case ServerTagClass.Declaration:
             if (CurrentToken.Class == TokenClass.Identifier) {
                 tag.NameToken.Read();
                 ParseAttributes(tag.Attributes);
                 if (CurrentToken.Class == TokenClass.ServerTagEnd) {
                     tag.EndToken.Read();
                     tag.NewLineAfter.ReadNewLineAfter();
                     return true;
                 } else {
                     Error("Server tag {0}: closing bracket expected.", tag.FullName);
                     tag.EndToken.Class = TokenClass.ServerTagEnd; tag.EndToken.ServerTagClass = tag.StartToken.ServerTagClass;
                     SkipTo(TokenClass.ServerTagEnd, TokenClass.TagStart);
                 }
             } else {
                 Error("Server tag {0}: identifier expected.", tag.FullName);
                 tag.NameToken.Class = TokenClass.Identifier; tag.NameToken.Value = "_error";
                 tag.EndToken.Class = TokenClass.ServerTagEnd; tag.EndToken.ServerTagClass = tag.StartToken.ServerTagClass;
                 SkipTo(TokenClass.ServerTagEnd, TokenClass.TagStart);
             }
             break;
         case ServerTagClass.Binding:
         case ServerTagClass.Code:
         case ServerTagClass.Expression:
         case ServerTagClass.Comment:
         case ServerTagClass.AspNetExpression:
         case ServerTagClass.HtmlEncodedExpression:
             if (CurrentToken.Class == TokenClass.Literal) {
                 tag.ValueToken.Read();
                 if (CurrentToken.Class == TokenClass.ServerTagEnd) {
                     tag.EndToken.Read();
                 }
             }
             break;
         }
     } else Error("Server Tag: server tag expected.");
     return false;
 }
Example #19
0
 public virtual void ImportServerTag(ServerTag tag)
 {
     ImportToken(tag.StartToken);
     if (tag.StartToken.ServerTagClass == ServerTagClass.Declaration) { ImportToken(tag.NameToken); ImportAttributes(tag.Attributes); } else ImportToken(tag.ValueToken);
     ImportToken(tag.EndToken);
     ImportNewLineAfter(tag.NewLineAfter);
 }