Esempio n. 1
0
        public virtual bool Send(Message message)
        {
            if (message == null)
            {
                return(true);
            }
            byte[] message_text = message.MessageText;
            message_text = Message.Encode(message_text);
            bool val = true;

            try
            {
                lock (this.socketSync)
                {
                    int sent = _sock.Send(message_text);
                    if ((message_text.Length * 2) != sent)
                    {
                        val = false;
                    }

                    this.BytesSent += sent;
                }
            }
            catch (Exception ex)
            {
                PhazeXLog.LogError(ex, GameLibraryVersion.VersionString, 103);
                Disconnect();
                return(false);
            }
            return(val);
        }
Esempio n. 2
0
        public void Disconnect()
        {
            try
            {
                lock (this.socketSync)
                {
                    _connected = false;
                    if (_sock != null)
                    {
                        _sock.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                PhazeXLog.LogError(ex, GameLibraryVersion.VersionString, 101);
            }

            try
            {
                if (_serverGame != null)
                {
                    _serverGame.Cancel();
                }
            }
            catch (Exception ex)
            {
                PhazeXLog.LogError(ex, GameLibraryVersion.VersionString, 102);
            }
        }
Esempio n. 3
0
 private void handleSystemMessage(SystemMessage m, ServerPlayer p)
 {
     //client tried to send system message
     //message should be logged somewhere!
     //but we will NOT pass it on to the clients
     //should we write the system message? sure, it's just a text file
     PhazeXLog.LogWarning("Client (" + p.Name + ") told the server a system message." + m.ToString(), GameLibraryVersion.ProgramIdentifier, 0);
     return;
 }
Esempio n. 4
0
 public void LoginAckTimeout(object o)
 {
     //this function is called when the server doesn't respond in some number of seconds!
     lock (this)
     {
         if (!_loggedIn)
         {
             PhazeXLog.LogError(
                 new Exception("Didn't get login acknowledgement in " + TimingDefinitions.LoginTimeout_Client + " ms")
                 , GameLibraryVersion.VersionString, 0);
             this.Disconnect();
         }
     }
 }
Esempio n. 5
0
        public void AddPlayer(Player player)
        {
            ExceptionHelpers.CheckNotNull(player, "player");

            player.PlayerID = this.unusedPlayerID;
            this.unusedPlayerID++;
            this.players.Add(player);

            if (this.players.Count == this.Rules.MaximumPlayers)
            {
                PhazeXLog.LogInformation("Reached player limit, starting game.");
                this.StartGame();
            }
        }
Esempio n. 6
0
 public ConnServer(ServerGame sg, GameRules rules, NetworkSettings settings)
 {
     this.rules    = rules;
     this.settings = settings;
     _serverGame   = sg;
     _port         = this.settings._Port;
     _process      = true;
     try
     {
         _connectionListener = new TcpListener(IPAddress.Any, _port);
         _bound = true;
     }
     catch (Exception e)
     {
         PhazeXLog.LogError(e, GameLibraryVersion.VersionString, 105);
         _bound   = false;
         _process = false;
         throw e;
     }
 }
Esempio n. 7
0
        public void Start()
        {
            bool cl_started = false;

            if (_process)
            {
                try
                {
                    _connectionListener.Start();

                    //while (_connectionListener.Server == null) continue;
                    //while (!_connectionListener.Server.Poll(50, SelectMode.SelectRead)) continue;
                    cl_started = true;
                }
                catch (Exception e)
                {
                    PhazeXLog.LogError(e, GameLibraryVersion.VersionString, 106);
                    _process = false;
                }
            }

            while (_process)
            {
                try
                {
                    bool b = false;
                    lock (this)
                    {
                        if (_connectionListener != null)
                        {
                            b = _connectionListener.Pending();
                        }
                    }
                    if (!b)
                    {
                        Thread.Sleep(TimingDefinitions.ConnectionListener_Pending);
                        continue;
                    }
                    Socket sck = null;
                    lock (this)
                    {
                        if (_connectionListener == null)
                        {
                            sck = null;
                        }
                        else
                        {
                            sck = _connectionListener.AcceptSocket();
                        }
                    }
                    if (sck == null)
                    {
                        continue;
                    }
                    new ServerPlayer(sck, _serverGame);
                    if (_serverGame.PlayerCount() == this.rules.MaximumPlayers)
                    {
                        lock (this)
                        {
                            _process = false;
                        }
                    }
                }
                catch (Exception e)
                {
                    PhazeXLog.LogError(e, GameLibraryVersion.VersionString, 0);
                    continue;
                }
            }
            if (cl_started)
            {
                if (_connectionListener != null)
                {
                    _connectionListener.Stop();
                }
            }
        }
Esempio n. 8
0
        public void Login(int major, int minor, int build, string client_title)
        {
            if (_loggedIn)
            {
                return;
            }
            _loggedIn = false;
            Send(new LoginMessage(
                     this.playerSettings._Name
                     , 0
                     , _readyToPlay
                     , _computerPlayer
                     , true
                     , major
                     , minor
                     , build
                     , client_title
                     , System.Environment.Version.ToString()
                     , System.Environment.OSVersion.ToString()
                     , GameLibraryVersion.Major
                     , GameLibraryVersion.Minor
                     , GameLibraryVersion.Build));

            //start timeout
            new System.Threading.Timer
            (
                new TimerCallback(this.LoginAckTimeout)
                , null
                , TimingDefinitions.LoginTimeout_Client
                , Timeout.Infinite
            );



            //go through all messages received and wait for a login acknowledgement
            Message m = null;
            bool    login_acknowledged = false;

            while ((!login_acknowledged) && (_connected))
            {
                try
                {
                    m = this.getMessage();
                    if (m == null)
                    {
                        Thread.Sleep(TimingDefinitions.GetMessage_Client);
                        continue;
                    }
                    if (m.GetType().Equals(typeof(LoginAckMessage)))
                    {
                        LoginAckMessage lam = (LoginAckMessage)m;
                        lock (this)
                        {
                            _loggedIn      = true;
                            this._playerID = lam.Id;
                        }
                        login_acknowledged = true;
                    }
                }
                catch (BadMessageException bme)
                {
                    PhazeXLog.LogError(bme, "Client", 0);
                    login_acknowledged = false;
                }
            }

            if ((!_connected) || (!login_acknowledged))
            {
                throw new LoginException("Login not acknowledged within " + TimingDefinitions.LoginTimeout_Client + "ms. Server may have died?");
            }



            Player me = new Player(false);

            me.Name             = this.playerSettings._Name;
            me.PlayerID         = _playerID;
            me.Release          = major;
            me.Revision         = minor;
            me.Build            = build;
            me.ClientTitle      = client_title;
            me.LibRelease       = GameLibraryVersion.Major;
            me.LibRevision      = GameLibraryVersion.Minor;
            me.LibBuild         = GameLibraryVersion.Build;
            me.FrameworkVersion = System.Environment.Version.ToString();
            me.OSVersion        = System.Environment.OSVersion.ToString();
            AddPlayer(me);
            return;
        }
Esempio n. 9
0
        protected Message getMessage()
        {
            byte[] b;
            int    avail;

            try
            {
                //while we're here, look for data in the buffer
                avail = _sock.Available;
                if (avail > 0)
                {
                    buffer.ReadFromSocket(_sock, avail);

                    this.BytesReceived += avail;
                }

                //first see if we can actually decode something
                if (buffer.CanDecode())
                {
                    b = buffer.Decode();
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                PhazeXLog.LogError(ex, GameLibraryVersion.VersionString, 104);
                _connected = false;
                return(null);
            }



            Message m = null;

            if (b.Length == 0)
            {
                return(m);
            }
            else if (b[0] == (byte)pxMessages.Heartbeat)
            {
                m = new HeartBeatMessage(b);
            }
            else if (b[0] == (byte)pxMessages.ChangeName)
            {
                m = new ChangeNameMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.ChangeNameReject)
            {
                m = new ChangeNameRejectMessage(b);
            }
            else if (b[0] == (byte)pxMessages.Chat)
            {
                m = new ChatMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.CompletedPhaze)
            {
                m = new CompletedPhazeMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.CurrentPhaze)
            {
                m = new CurrentPhazeMessage(b, this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.DiscardSkip)
            {
                m = new DiscardSkipMessage(b, this.GetPlayerIDs(), this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.DialogMessage)
            {
                m = new DialogMessage(b);
            }
            else if (b[0] == (byte)pxMessages.ErrorMessage)
            {
                m = new ErrorMessage(b);
            }
            else if (b[0] == (byte)pxMessages.GameOver)
            {
                m = new GameOverMessage(b);
            }
            else if (b[0] == (byte)pxMessages.GameRules)
            {
                m = new GameRulesMessage(b);
            }
            else if (b[0] == (byte)pxMessages.GameStarting)
            {
                m = new GameStartingMessage(b);
            }
            else if (b[0] == (byte)pxMessages.Goodbye)
            {
                m = new GoodbyeMessage(b);
            }
            else if (b[0] == (byte)pxMessages.GotCards)
            {
                m = new GotCardsMessage(b, this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.GotDeckCard)
            {
                m = new GotDeckCardMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.GotDiscard)
            {
                m = new GotDiscardMessage(b, this.GetPlayerIDs(), this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.Hand)
            {
                m = new HandMessage(b, this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.Login)
            {
                m = new LoginMessage(b);
            }
            else if (b[0] == (byte)pxMessages.LoginAcknowledgment)
            {
                m = new LoginAckMessage(b);
            }
            else if (b[0] == (byte)pxMessages.LogOff)
            {
                m = new LogOffMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.NewHand)
            {
                m = new NewHandMessage(b);
            }
            else if (b[0] == (byte)pxMessages.PlayedCardOnTable)
            {
                m = new PlayedCardOnTableMessage(b, this.GetPlayerIDs(), this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.Ready)
            {
                m = new ReadyMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.Scoreboard)
            {
                m = new ScoreboardMessage(b, this.GetPlayerIDs(), this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.SkipNotification)
            {
                m = new SkipNotificationMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.StartGameTimer)
            {
                m = new StartGameTimerMessage(b);
            }
            else if (b[0] == (byte)pxMessages.Status)
            {
                m = new StatusMessage(b, this.GetPlayerIDs(), this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.SystemMessage)
            {
                m = new SystemMessage(b);
            }
            else if (b[0] == (byte)pxMessages.Table)
            {
                m = new TableMessage(b, this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.TurnEnd)
            {
                m = new TurnEndMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.TurnStart)
            {
                m = new TurnStartMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.UpdateDiscard)
            {
                m = new UpdateDiscardMessage(b, this.GetPlayerIDs(), this.GameRules);
            }
            else if (b[0] == (byte)pxMessages.WentOut)
            {
                m = new WentOutMessage(b, this.GetPlayerIDs());
            }
            else if (b[0] == (byte)pxMessages.Won)
            {
                m = new WonMessage(b, this.GetPlayerIDs());
            }
            else
            {
                m = new UnknownMessage(b);
            }

            return(m);
        }
Esempio n. 10
0
        public virtual void Connect()
        {
            //connect
            try
            {
                IPHostEntry iphe;

                string address = this.networkSettings._Hostname;

                if (address.Equals("127.0.0.1"))
                {
                    try
                    {
                        IPEndPoint ipe = new IPEndPoint(IPAddress.Loopback, this.networkSettings._Port);
                        Socket     s   = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        s.NoDelay = true;
                        s.Connect(ipe);
                        _sock = s;


                        //set up heartbeat!
                        Thread t = new Thread(new ThreadStart(this.DoHeartbeat));
                        t.Name = "Heartbeat Thread to server";
                        t.Start();
                    }
                    catch (Exception) {  }
                }
                else
                {
                    iphe = Dns.GetHostEntry(this.networkSettings._Hostname);

                    foreach (IPAddress ipa in iphe.AddressList)
                    {
                        //bug fix: on ipv6, sometimes the timeouts are too long
                        if (ipa.AddressFamily == AddressFamily.InterNetworkV6)
                        {
                            continue;
                        }
                        try
                        {
                            IPEndPoint ipe = new IPEndPoint(ipa, this.networkSettings._Port);
                            Socket     s   = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                            s.NoDelay = true;
                            s.Connect(ipe);
                            _sock = s;


                            //set up heartbeat!
                            Thread t = new Thread(new ThreadStart(this.DoHeartbeat));
                            t.Name = "Heartbeat Thread to server";
                            t.Start();
                            break;
                        }
                        catch (Exception) { continue; }
                    }
                }
            }
            catch (Exception e)
            {
                PhazeXLog.LogError(e, GameLibraryVersion.ProgramIdentifier, 100);
                _sock = null;
            }
            _connected = (_sock != null);

            return;
        }
Esempio n. 11
0
 private void handleMessage(Message m, ServerPlayer p)
 {
     lock (this)
     {
         try
         {
             if (m == null)
             {
                 return;
             }
             if (m.GetType().Equals(typeof(HeartBeatMessage)))
             {
                 handleHeartBeatMessage((HeartBeatMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(SystemMessage)))
             {
                 handleSystemMessage((SystemMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(ChatMessage)))
             {
                 handleChatMessage((ChatMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(ReadyMessage)))
             {
                 handleReadyMessage((ReadyMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(ChangeNameMessage)))
             {
                 handleChangeNameMessage((ChangeNameMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(PlayOnGroupMessage)))
             {
                 handlePlayOnGroupMessage((PlayOnGroupMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(MeldMessage)))
             {
                 handleMeldMessage((MeldMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(GetTopDiscardMessage)))
             {
                 handleGetTopDiscardMessage((GetTopDiscardMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(GetTopDeckCardMessage)))
             {
                 handleGetTopDeckCardMessage((GetTopDeckCardMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(DiscardSkipMessage)))
             {
                 handleDiscardSkipMessage((DiscardSkipMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(DiscardMessage)))
             {
                 handleDiscardMessage((DiscardMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(RequestHandMessage)))
             {
                 handleRequestHandMessage((RequestHandMessage)m, p);
             }
             else if (m.GetType().Equals(typeof(RequestTableMessage)))
             {
                 handleRequestTableMessage((RequestTableMessage)m, p);
             }
             else
             {
                 UnknownMessage um = (UnknownMessage)m;
                 PhazeXLog.LogError
                 (
                     new Exception("Unknown message from client received! [" + um.Identifier + "]")
                     , GameLibraryVersion.ProgramIdentifier
                     , 108
                 );
             }
         }
         catch (BadMessageException bme)
         {
             PhazeXLog.LogError
             (
                 bme
                 , GameLibraryVersion.ProgramIdentifier
                 , 0
             );
         }
     }
 }
Esempio n. 12
0
        public void AddMessageToProcess(ServerPlayer sp, byte [] b)
        {
            if (b.Length < 1)
            {
                PhazeXLog.LogError
                (
                    new Exception("Attempted to process 0 byte message!")
                    , GameLibraryVersion.ProgramIdentifier
                    , 0
                );
            }
            byte start = b[0];

            try
            {
                Message msg = null;
                switch (start)
                {
                case (byte)pxMessages.Heartbeat:
                    msg = new HeartBeatMessage(b);
                    break;

                case (byte)pxMessages.SystemMessage:
                    msg = new SystemMessage(b);
                    break;

                case (byte)pxMessages.Chat:
                    msg = new ChatMessage(b, this.getIDs());
                    break;

                case (byte)pxMessages.Ready:
                    msg = new ReadyMessage(b, this.getIDs());
                    break;

                case (byte)pxMessages.ChangeName:
                    msg = new ChangeNameMessage(b, this.getIDs());
                    break;

                case (byte)pxMessages.PlayOnGroup:
                    msg = new PlayOnGroupMessage(b, this.rules);
                    break;

                case (byte)pxMessages.Meld:
                    msg = new MeldMessage(b, this.rules);
                    break;

                case (byte)pxMessages.GetTopDiscard:
                    msg = new GetTopDiscardMessage(b);
                    break;

                case (byte)pxMessages.GetTopDeckCard:
                    msg = new GetTopDeckCardMessage(b);
                    break;

                case (byte)pxMessages.DiscardSkip:
                    msg = new DiscardSkipMessage(b, this.getIDs(), this.rules);
                    break;

                case (byte)pxMessages.Discard:
                    msg = new DiscardMessage(b, this.rules);
                    break;

                case (byte)pxMessages.RequestHand:
                    msg = new RequestHandMessage(b);
                    break;

                case (byte)pxMessages.RequestTable:
                    msg = new RequestTableMessage(b);
                    break;

                default:
                    msg = new UnknownMessage(b);
                    break;
                }
                lock (this)
                {
                    _messagesToProcess.Add(new PlayerMessage(sp, msg));
                }
            }
            catch (BadMessageException bme)
            {
                PhazeXLog.LogError
                (
                    bme
                    , GameLibraryVersion.ProgramIdentifier
                    , 109
                );

                string info = "";
                foreach (byte tmp in b)
                {
                    info += ((int)tmp).ToString() + " ";
                }
                PhazeXLog.LogInformation(info, pid);
            }
        }
Esempio n. 13
0
        private void listenForLogin()
        {
            try
            {
                int avail;

                //as long as we're listening and not logged in
                while ((_listening) && (!this.LoggedIn))
                {
                    //save socketAvailable locally as it may grow (but not shrink as there is only
                    //one thread removing data from _socket)

                    //if (!_socket.Poll(TimingDefinitions.ListenSocket_Server, SelectMode.SelectRead)) continue;
                    avail = _socket.Available;
                    if (avail == 0)
                    {
                        Thread.Sleep(TimingDefinitions.ListenSocket_Server);
                        continue;
                    }


                    //read the data
                    _buffer.ReadFromSocket(_socket, avail);
                    _serverGame.ReceivedBytes((ulong)avail);

                    bool validated = false;

                    //while we can decode something in messages
                    while (_buffer.CanDecode())
                    {
                        //get the first decodable message and save the rest back into messages
                        byte[] b = _buffer.Decode();

                        //figure out if it's a login message
                        LoginMessage lm = null;
                        if (b[0] == (byte)pxMessages.Login)
                        {
                            try
                            {
                                //create a new login message. if it throws an exception, then
                                //we couldn't validate the login message
                                lm        = new LoginMessage(b);
                                validated = true;
                            }
                            catch (BadMessageException bme)
                            {
                                PhazeXLog.LogError(bme, GameLibraryVersion.ProgramIdentifier, 0);
                                validated = false;
                            }

                            if (validated)
                            {
                                //log this into the game
                                lock (this)
                                {
                                    this.LoggedIn = true;
                                }
                                StartListeningThread();
                                lock (this)
                                {
                                    _serverGame.LoginPlayer(this, lm);
                                }
                            }
                        }
                    }
                }
            }
            catch (SocketException ex)
            {
                PhazeXLog.LogError(ex, pid, 0);
                Disconnect();
            }
            return;
        }