示例#1
0
        /// <summary>
        ///     Start and Connect a new <see cref="IClient{T}" />
        /// </summary>
        /// <typeparam name="T">The Type of object to send over the network</typeparam>
        /// <param name="address">The <see cref="IServer{T}" />'s <see cref="IPAddress" /></param>
        /// <param name="port">The <see cref="IServer{T}" />'s Port</param>
        /// <param name="newThread">
        ///     Whether to use a seperate
        ///     <see cref="System.Threading.Thread" /> for all data transfers
        /// </param>
        /// <returns>A connected <see cref="IClient{T}" /> instance</returns>
        public static async Task <IClient <T> > StartNewClient <T>(string address, int port, bool newThread)
        {
            var client = new ProtoClient <T>(IPAddress.Parse(address), port);
            await client.Connect(newThread);

            return(client);
        }
 private async void SendPersonalUpdate()
 {
     if (worldState.Location == null)
     {
         worldState.Trajectory = new Trajectory()
         {
             X = 0f, Y = 0f, Z = 0f
         };
     }
     else
     {
         //worldState.Trajectory.X = (transform.position.x - worldState.Location.X) / 4f;
         //worldState.Trajectory.Y = 0f;
         //worldState.Trajectory.Z = (transform.position.z - worldState.Location.Z) / 4f;
         var rb = GetComponent <Rigidbody>();
         worldState.Trajectory.X = rb.velocity.x;
         worldState.Trajectory.Y = rb.velocity.y;
         worldState.Trajectory.Z = rb.velocity.z;
     }
     worldState.Location              = new Location();
     worldState.Location.X            = transform.position.x;
     worldState.Location.Y            = transform.position.y;
     worldState.Location.Z            = transform.position.z;
     worldState.Orientation           = new Orientation();
     worldState.Orientation.X         = transform.rotation.x;
     worldState.Orientation.Y         = transform.rotation.y;
     worldState.Orientation.Z         = transform.rotation.z;
     worldState.Orientation.W         = transform.rotation.w;
     worldState.AnimationState        = new AnimationState();
     worldState.HealthAndStatus       = new HealthAndStatus();
     worldState.HealthAndStatus.Level = GetComponent <ExperienceGainer>().level;
     SetAnimationState(this);
     await Task.Run(() => ProtoClient.UpdatePersonalWorldState(worldState));
 }
示例#3
0
        private static async Task HttpPostRequest(string endpoint, IMessage message)
        {
            IClient protoClient = new ProtoClient("https://localhost:5001/");

            var result = await protoClient.Post <Person>(endpoint, message);

            Console.WriteLine(result.ToString());
        }
示例#4
0
        public EndpointRoutingSampleTest()
        {
            var gameHostBuilder = Program.GetGameHostBuilder(new[] { Program.EndpointRoutingScenario, });

            _testServer         = new TestServer(gameHostBuilder);
            _client             = _testServer.CreateClient();
            _client.BaseAddress = new Uri("http://localhost");
        }
示例#5
0
 private static void StartClient()
 {
     _client = new ProtoClient <string>(ServerIp, 1024);
     _client.AutoReconnect = true;
     _client.Connect().GetAwaiter().GetResult();
     _client.ReceivedMessage += ClientMessageReceived;
     _client.ConnectionLost  += Client_ConnectionLost;
     _client.Send("Hello Server!").GetAwaiter().GetResult();
 }
 void Start()
 {
     try {
         ProtoClient.Login();
         UpdateGameList();
     }
     catch (Exception e) {
         LoadInitialScene();
     }
 }
示例#7
0
文件: Client.cs 项目: roachadam/Salvo
 public Client(string ipAddress)
 {
     _client = new ProtoClient <SalvoData>(IPAddress.Parse(ipAddress), 51111)
     {
         AutoReconnect     = true,
         ReceiveBufferSize = 1024 * 10,
         SendBufferSize    = 1024 * 10
     };
     _client.ReceivedMessage += ClientMessageReceived;
     _client.ConnectionLost  += Client_ConnectionLost;
 }
 private void UpdateGameList()
 {
     gameList = ProtoClient.GetActiveGames();
     foreach (Transform child in buttonContainer.transform)
     {
         Destroy(child);
     }
     foreach (var game in gameList.Games)
     {
         AddGameButton(game);
     }
 }
        /// <summary>
        /// Performs a synchronous RPC operation on the given service.
        /// </summary>
        /// <typeparam name="TService">The service being used.</typeparam>
        /// <param name="client">The client to use to invoke the RPC call.</param>
        /// <param name="operation">An expression indicating the operation to perform.</param>
        public static void Invoke <TService>(
            this ProtoClient <TService> client,
            Expression <Action <TService> > operation) where TService : class
        {
            Action updateArgs;

            object[]   args;
            MethodInfo method = ResolveMethod <TService>(operation, out updateArgs, out args);

            client.Invoke(method, args);
            if (updateArgs != null)
            {
                updateArgs();
            }
        }
示例#10
0
        public EndpointRoutingBenchmarkTest()
        {
            // This switch and value are set by benchmark server when running the app for profiling.
            var args            = new[] { "--scenarios", "PlaintextEndpointRouting" };
            var gameHostBuilder = Benchmarks.Program.GetGameHostBuilder(args);

            // Make sure we are using the right startup
            var startupName = gameHostBuilder.GetSetting("Startup");

            Assert.Equal(nameof(Benchmarks.StartupUsingEndpointRouting), startupName);

            _testServer         = new TestServer(gameHostBuilder);
            _client             = _testServer.CreateClient();
            _client.BaseAddress = new Uri("http://localhost");
        }
示例#11
0
文件: Program.cs 项目: qcjxberin/ec
        static void Main(string[] args)
        {
            System.Threading.Timer mTimer;

            try
            {
                DateTime dt;
                ProtoClient client = new ProtoClient("127.0.0.1");
                client.Receive = (o, e) =>
                {
                    Console.WriteLine("Receive From Server:{0}", e.Message);
                };
                User user = new User { EMail = "*****@*****.**", Name = "henry" };
                client.Send(user);
                IUserService us = client.CreateInstance<IUserService>();
                user = us.Register(user);
                Console.WriteLine(user.CreateTime);


                user = us.Register("henry", null);
                Console.WriteLine(user.CreateTime);

                user = us.Register("henry", "*****@*****.**", out dt);
                Console.WriteLine(dt);

                user = us.ReturnNull();
                Console.WriteLine(user == null);


                us.GetTime(out dt);

                Console.WriteLine(dt);
                //mTimer = new System.Threading.Timer(d =>
                //{
                //    DateTime s;
                //    us.GetTime(out s);
                //    Console.WriteLine(s);
                //}, null, 1000, 1000);

            }
            catch (Exception e_)
            {
                Console.WriteLine(e_);
            }
            Console.Read();


        }
        /// <summary>
        /// Performs an asynchronous RPC operation on the given service.
        /// </summary>
        /// <typeparam name="TService">The service being used.</typeparam>
        /// <param name="client">The client to use to invoke the RPC call.</param>
        /// <param name="operation">An expression indicating the operation to perform.</param>
        /// <param name="callback">A delegate that is invoked when the operation is complete. The
        /// callback is additionally given an `Action` that can be invoked to raise any exception
        /// associated with the call.</param>
        public static void InvokeAsync <TService>(this ProtoClient <TService> client, Expression <Action <TService> > operation, Action <Action> callback) where TService : class
        {
            Action updateArgs;

            object[]   args;
            MethodInfo method = ResolveMethod <TService>(operation, out updateArgs, out args);

            client.InvokeAsync(method, result =>
            {
                if (updateArgs != null)
                {
                    updateArgs();
                }
                callback(() => { result(); });
            });
        }
        /// <summary>
        /// Performs a synchronous RPC operation on the given service.
        /// </summary>
        /// <typeparam name="TService">The service being used.</typeparam>
        /// <typeparam name="TResult">The result of the RPC call.</typeparam>
        /// <param name="client">The client to use to invoke the RPC call.</param>
        /// <param name="operation">An expression indicating the operation to perform.</param>
        /// <returns>The value of the RPC call.</returns>
        public static TResult Invoke <TService, TResult>(
            this ProtoClient <TService> client,
            Expression <Func <TService, TResult> > operation) where TService : class
        {
            Action updateArgs;

            object[]   args;
            MethodInfo method = ResolveMethod <TService>(operation, out updateArgs, out args);
            TResult    result = (TResult)client.Invoke(method, args);

            if (updateArgs != null)
            {
                updateArgs();
            }
            return(result);
        }
示例#14
0
文件: Program.cs 项目: zhyzhy782/ec
        static void Main(string[] args)
        {
            System.Threading.Timer mTimer;

            try
            {
                DateTime    dt;
                ProtoClient client = new ProtoClient("127.0.0.1");
                client.Receive = (o, e) =>
                {
                    Console.WriteLine("Receive From Server:{0}", e.Message);
                };
                User user = new User {
                    EMail = "*****@*****.**", Name = "henry"
                };
                client.Send(user);
                IUserService us = client.CreateInstance <IUserService>();
                user = us.Register(user);
                Console.WriteLine(user.CreateTime);


                user = us.Register("henry", null);
                Console.WriteLine(user.CreateTime);

                user = us.Register("henry", "*****@*****.**", out dt);
                Console.WriteLine(dt);

                user = us.ReturnNull();
                Console.WriteLine(user == null);


                us.GetTime(out dt);

                Console.WriteLine(dt);
                //mTimer = new System.Threading.Timer(d =>
                //{
                //    DateTime s;
                //    us.GetTime(out s);
                //    Console.WriteLine(s);
                //}, null, 1000, 1000);
            }
            catch (Exception e_)
            {
                Console.WriteLine(e_);
            }
            Console.Read();
        }
示例#15
0
        /// <summary>
        /// Take a client's log in details, verify them and then choose to either allow the user to log in, or disconnect
        /// </summary>
        /// <param name="login">Log in details</param>
        /// <param name="c">Client who is logging in</param>
        /// <returns>Boolean indicating whether log in was successful</returns>
        public static bool ProcessLogIn(ProtoLogIn login, Client c)
        {
            Contract.Requires(c != null && login != null);
            if (!VerifyUser(c.username, login.userSalt))
            {
                return(false);
            }
            try
            {
                if (login.Key != null)
                {
                    byte[] key = rsa.Decrypt(login.Key, false);
                    // Key must be non-null and long enough

                    if (key == null || key.Length < 5)
                    {
                        return(false);
                    }
                    c.alg = new NetAESEncryption(Globals_Server.server, key, 0, key.Length);
                }
                else
                {
#if ALLOW_UNENCRYPT
                    c.alg = null;
#else
                    return(false);
#endif
                }
                ProtoClient clientDetails = new ProtoClient(c);
                clientDetails.ActionType   = Actions.LogIn;
                clientDetails.ResponseType = DisplayMessages.LogInSuccess;
                Server.SendViaProto(clientDetails, c.conn, c.alg);
                Globals_Game.RegisterObserver(c);
                return(true);
            }
            catch (Exception e)
            {
#if DEBUG
                Console.WriteLine("Failure during decryption: " + e.GetType() + " " + e.Message + ";" + e.StackTrace);
#endif
                return(false);
            }
        }
示例#16
0
    public static bool Login(string username, string password, out string reason)
    {
        reason = null;
        //tclient.LogInAndConnect(username, password, "localhost");
        tclient.LogInAndConnect(username, password, "92.239.228.86");

        //bool loggedIn = false;
        //while(!loggedIn){
        //    ProtoMessage reply = GetActionReply(Actions.LogIn, tclient);
        //    if(reply.ResponseType == DisplayMessages.LogInFail) {
        //        return false;
        //    }
        //    else if(reply.ResponseType == DisplayMessages.None){

        //    }
        //    else if(reply.ResponseType == DisplayMessages.LogInSuccess) {
        //        loggedIn = true;
        //    }
        //}

        Debug.Log("made it out of LogInAndConnect");

        int          i     = 1;
        ProtoMessage reply = null;

        while (!tclient.IsConnectedAndLoggedIn())
        {
            reply = GetActionReply(Actions.LogIn, tclient);
            if (reply == null)
            {
                reason = "Log in request timed out.";
                return(false);
            }
            if (reply.ResponseType == DisplayMessages.LogInFail)
            {
                reason = "Wrong username or password.";
                return(false);
            }
            if (reply.ResponseType == DisplayMessages.LogInSuccess)
            {
                break;
            }

            Debug.Log("I'm still waiting: " + i.ToString());
            i++;
        }

        protoClient = (ProtoClient)reply;
        return(true);


        //while (!tclient.IsConnectedAndLoggedIn())
        //{
        //    Thread.Sleep(0);
        //}

        //if (tclient.IsConnectedAndLoggedIn())
        //{
        //   // mf = GetFiefDetails(tclient);

        //    GoToScene("MainMenu");

        //    //SceneManager.LoadScene("MainMenu");
        //    // FiefControl f = new FiefControl(tclient);
        //}
    }
示例#17
0
    public static ProtoMessage GetActionReply(Actions action, TextTestClient client)
    {
        bool         receivedActionReply = false;
        bool         receivedUpdateReply = false;
        ProtoMessage reply;
        ProtoMessage actionReply = null;

        if (action == Actions.LogIn)
        {
            receivedUpdateReply = true;
        }

        //int elapsed = 0;
        do
        {
            //reply = client.GetReply();
            reply = client.CheckForProtobufMessage();
            if (reply == null)  // wait time expired.
            {
                globalString = "You have been disconnected.";
                tclient.LogOut();
                GoToScene(SceneName.LogIn);
                return(null);
            }

            if (reply.ActionType == action)
            {
                Debug.Log("Correct action found: " + reply.ActionType.ToString() + " /w " + reply.ResponseType.ToString());
                actionReply         = reply;
                receivedActionReply = true;
            }
            else if (reply.ActionType == Actions.Update)
            {
                Debug.Log("Update action found: " + reply.ActionType.ToString() + " /w " + reply.ResponseType.ToString());
                if (reply.ResponseType == DisplayMessages.ErrorGenericMessageInvalid)
                {
                    actionReply         = reply; // When the server found something wrong with the action.
                    receivedActionReply = true;
                }
                //else if(reply.ResponseType == DisplayMessages.Error) {
                //    receivedUpdateReply = true; // LogIn Failure.
                //}
                else if (reply.ResponseType == DisplayMessages.Success)
                {
                    protoClient         = (ProtoClient)reply;
                    receivedUpdateReply = true;
                }
            }
            else
            {
                Debug.Log("Mismatching action found: " + reply.ActionType.ToString() + " /w " + reply.ResponseType.ToString());
            }

//            Thread.Sleep(10);
//            elapsed += 10;
//            if(elapsed > 5000) {
//#if UNITY_EDITOR
//                UnityEditor.EditorApplication.isPlaying = false;
//#endif
//            }
        } while(!receivedActionReply || !receivedUpdateReply);

        return(actionReply);

        //ProtoMessage responseTask = client.GetReply();

        //while(responseTask.ActionType != action) {
        //    responseTask = client.GetReply();
        //}
        //client.ClearMessageQueues();
        //return responseTask;
    }
    public void CreateNewGame()
    {
        var game = ProtoClient.CreateGame(nameInput.text);

        SelectGame(game);
    }
示例#19
0
 private String GetProtoInitFailedMsg(ProtoClient protoClient)
 {
     return($"Failed to connect to Hyperion server using {protoClient}");
 }
示例#20
0
        public void Listen()
        {
            while (server.Status == NetPeerStatus.Running && !ctSource.Token.IsCancellationRequested)
            {
                NetIncomingMessage im;
                WaitHandle.WaitAny(new WaitHandle[] { server.MessageReceivedEvent, ctSource.Token.WaitHandle });
                while ((im = server.ReadMessage()) != null && !ctSource.Token.IsCancellationRequested)
                {
                    switch (im.MessageType)
                    {
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.ErrorMessage:
                    case NetIncomingMessageType.WarningMessage:
                        Globals_Server.logError("Recieved warning message: " + im.ReadString());
                        break;

                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.Data:
                    {
#if DEBUG
                        Console.WriteLine("SERVER: recieved data message");
#endif
                        if (!clientConnections.ContainsKey(im.SenderConnection))
                        {
                            //error
                            im.SenderConnection.Disconnect("Not recognised");
                            return;
                        }
                        Client c = clientConnections[im.SenderConnection];
                        if (c.alg != null)
                        {
                            im.Decrypt(c.alg);
                        }
                        ProtoMessage m = null;
                        //global::ProtoMessage.ProtoMessage y = null;
                        using (MemoryStream ms = new MemoryStream(im.Data))
                        {
                            try
                            {
                                //y = Serializer.DeserializeWithLengthPrefix<global::ProtoMessage.ProtoMessage>(ms,
                                //PrefixStyle.Fixed32);
                                m = Serializer.DeserializeWithLengthPrefix <ProtoMessage>(ms, PrefixStyle.Fixed32);
                            }
                            catch (Exception e)
                            {
                                NetOutgoingMessage errorMessage = server.CreateMessage(
                                    "Failed to deserialise message. The message may be incorrect, or the decryption may have failed.");
                                if (c.alg != null)
                                {
                                    errorMessage.Encrypt(c.alg);
                                }
                                server.SendMessage(errorMessage, im.SenderConnection,
                                                   NetDeliveryMethod.ReliableOrdered);
                                Globals_Server.logError("Failed to deserialize message for client: " + c.username);
                            }
                        }
                        if (m == null /*&& y == null*/)
                        {
                            string error = "Recieved null message from " + im.SenderEndPoint.ToString();
                            if (clientConnections.ContainsKey(im.SenderConnection))
                            {
                                error += ", recognised client " + clientConnections[im.SenderConnection];
                            }
                            else
                            {
                                error += ", unrecognised client (possible ping)";
                            }
                            error += ". Data: " + im.ReadString();
                            Globals_Server.logError(error);
                            break;
                        }

                        if (m.ActionType == Actions.LogIn)
                        {
                            ProtoLogIn login = m as ProtoLogIn;
                            if (login == null)
                            {
                                im.SenderConnection.Disconnect("Not login");
                                return;
                            }
                            lock (ServerLock)
                            {
                                if (LogInManager.VerifyUser(c.username, login.userSalt))
                                {
                                    if (LogInManager.ProcessLogIn(login, c))
                                    {
                                        string log = c.username + " logs in from " + im.SenderEndPoint.ToString();
                                        Globals_Server.logEvent(log);
                                    }
                                }
                                else
                                {
                                    ProtoMessage reply = new ProtoMessage
                                    {
                                        ActionType   = Actions.LogIn,
                                        ResponseType = DisplayMessages.LogInFail
                                    };
                                    im.SenderConnection.Disconnect("Authentication Fail");
                                }
                            }
                        }
                        // temp for testing, should validate connection first
                        else if (clientConnections.ContainsKey(im.SenderConnection))
                        {
                            if (Globals_Game.IsObserver(c))
                            {
                                ProcessMessage(m, im.SenderConnection);
                                ProtoClient clientDetails = new ProtoClient(c);
                                clientDetails.ActionType = Actions.Update;
                                SendViaProto(clientDetails, im.SenderConnection, c.alg);
                            }
                            else
                            {
                                im.SenderConnection.Disconnect("Not logged in- Disconnecting");
                            }
                        }

                        /*//IF Y ACTION
                         *  if (y.ActionType == global::ProtoMessage.Actions.LogIn)
                         *  {
                         *      global::ProtoMessage.Client forCheck = new global::ProtoMessage.Client(c.username, c.myPlayerCharacter.playerID);
                         *      global::ProtoMessage.ProtoLogIn login = y as global::ProtoMessage.ProtoLogIn;
                         *      if (login == null)
                         *      {
                         *          im.SenderConnection.Disconnect("Not login");
                         *          return;
                         *      }
                         *      lock (ServerLock)
                         *      {
                         *          if (LogInManager.VerifyUser(c.username, login.userSalt))
                         *          {
                         *              if (LogInManager.ProcessLogIn(login, forCheck, true))
                         *              {
                         *                  string log = c.username + " logs in from " + im.SenderEndPoint.ToString();
                         *                  Globals_Server.logEvent(log);
                         *              }
                         *          }
                         *          else
                         *          {
                         *              ProtoMessage reply = new ProtoMessage
                         *              {
                         *                  ActionType = Actions.LogIn,
                         *                  ResponseType = DisplayMessages.LogInFail
                         *              };
                         *              im.SenderConnection.Disconnect("Authentication Fail");
                         *          }
                         *      }
                         *  }
                         *  // temp for testing, should validate connection first
                         *  else if (clientConnections.ContainsKey(im.SenderConnection))
                         *  {
                         *      if (Globals_Game.IsObserver(c))
                         *      {
                         *          ProcessMessage(y, im.SenderConnection);
                         *          ProtoClient clientDetails = new ProtoClient(c);
                         *          clientDetails.ActionType = Actions.Update;
                         *          SendViaProto(clientDetails, im.SenderConnection, c.alg);
                         *      }
                         *      else
                         *      {
                         *          im.SenderConnection.Disconnect("Not logged in- Disconnecting");
                         *      }
                         *  }*/
                    }
                    break;

                    case NetIncomingMessageType.StatusChanged:
                        byte stat = im.ReadByte();
                        NetConnectionStatus status = NetConnectionStatus.None;
                        if (Enum.IsDefined(typeof(NetConnectionStatus), Convert.ToInt32(stat)))
                        {
                            status = (NetConnectionStatus)stat;
                        }
                        else
                        {
                            Globals_Server.logError("Failure to parse byte " + stat + " to NetConnectionStatus for endpoint " + im.ReadIPEndPoint());
                        }
                        if (status == NetConnectionStatus.Disconnected)
                        {
                            if (clientConnections.ContainsKey(im.SenderConnection))
                            {
                                Disconnect(im.SenderConnection);
                            }
                        }
                        break;

                    case NetIncomingMessageType.ConnectionApproval:
                    {
                        string senderID = im.ReadString();
                        string text     = im.ReadString();
                        Client client;
                        Globals_Server.Clients.TryGetValue(senderID, out client);
                        if (client != null)
                        {
                            ProtoLogIn logIn;
                            if (!LogInManager.AcceptConnection(client, text, out logIn))
                            {
                                im.SenderConnection.Deny();
                            }
                            else
                            {
                                NetOutgoingMessage msg = server.CreateMessage();
                                MemoryStream       ms  = new MemoryStream();
                                // Include X509 certificate as bytes for client to validate
                                Serializer.SerializeWithLengthPrefix <ProtoLogIn>(ms, logIn, PrefixStyle.Fixed32);
                                msg.Write(ms.GetBuffer());
                                clientConnections.Add(im.SenderConnection, client);
                                client.conn = im.SenderConnection;
                                im.SenderConnection.Approve(msg);
                                server.FlushSendQueue();
                                Globals_Server.logEvent("Accepted connection from " + client.username);
                            }
                        }
                        else
                        {
                            im.SenderConnection.Deny("unrecognised");
                        }
                    }

                    break;

                    case NetIncomingMessageType.ConnectionLatencyUpdated:
                        break;

                    default:
                        Globals_Server.logError("Received unrecognised incoming message type: " + im.MessageType);
                        break;
                    }
                    server.Recycle(im);
                }
            }
#if DEBUG
            Globals_Server.logEvent("Server listening thread exits");
#endif
        }
示例#21
0
        public void Listen()
        {
            while (server.Status == NetPeerStatus.Running && !ctSource.Token.IsCancellationRequested)
            {
                NetIncomingMessage im;
                WaitHandle.WaitAny(new WaitHandle[] { server.MessageReceivedEvent, ctSource.Token.WaitHandle });
                while ((im = server.ReadMessage()) != null && !ctSource.Token.IsCancellationRequested)
                {
                    if (im.SenderConnection != null)
                    {
                        Globals_Server.logEvent("Recieved: " + im.MessageType.ToString() + " | " + im.SenderConnection.RemoteEndPoint.ToString());
                    }
                    else
                    {
                        Globals_Server.logEvent("Recieved: " + im.MessageType.ToString() + " | NULL");
                    }

                    switch (im.MessageType)
                    {
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.ErrorMessage:
                    case NetIncomingMessageType.WarningMessage:
                        Globals_Server.logError("Recieved warning message: " + im.ReadString());
                        break;

                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.Data:
                    {
#if DEBUG
                        //Console.WriteLine("SERVER: recieved data message");
#endif
                        if (!clientConnections.ContainsKey(im.SenderConnection))
                        {
                            //error
                            im.SenderConnection.Disconnect("Not recognised");
                            return;
                        }
                        Client c = clientConnections[im.SenderConnection];
                        if (c.alg != null)
                        {
                            im.Decrypt(c.alg);
                        }
                        ProtoMessage m = null;
                        using (MemoryStream ms = new MemoryStream(im.Data))
                        {
                            try
                            {
                                m = Serializer.DeserializeWithLengthPrefix <ProtoMessage>(ms, PrefixStyle.Fixed32);
                            }
                            catch (Exception e)
                            {
                                NetOutgoingMessage errorMessage = server.CreateMessage(
                                    "Failed to deserialise message. The message may be incorrect, or the decryption may have failed.");
                                if (c.alg != null)
                                {
                                    errorMessage.Encrypt(c.alg);
                                }
                                server.SendMessage(errorMessage, im.SenderConnection,
                                                   NetDeliveryMethod.ReliableOrdered);
                                Globals_Server.logError("Failed to deserialize message for client: " + c.username);
                            }
                        }
                        if (m == null)
                        {
                            string error = "Recieved null message from " + im.SenderEndPoint.ToString();
                            if (clientConnections.ContainsKey(im.SenderConnection))
                            {
                                error += ", recognised client " + clientConnections[im.SenderConnection];
                            }
                            else
                            {
                                error += ", unrecognised client (possible ping)";
                            }
                            error += ". Data: " + im.ReadString();
                            Globals_Server.logError(error);
                            break;
                        }

                        if (m.ActionType == Actions.LogIn)
                        {
                            ProtoLogIn login = m as ProtoLogIn;
                            if (login == null)
                            {
                                im.SenderConnection.Disconnect("Received blank login message.");
                                return;
                            }
                            lock (ServerLock)
                            {
                                if (LogInManager.VerifyUser(c.username, login.userSalt))
                                {
                                    if (LogInManager.ProcessLogIn(login, c))
                                    {
                                        string log = c.username + " logs in from " + im.SenderEndPoint.ToString();
                                        Globals_Server.logEvent(log);
                                    }
                                }
                                else
                                {
                                    ProtoMessage reply = new ProtoMessage
                                    {
                                        ActionType   = Actions.LogIn,
                                        ResponseType = DisplayMessages.LogInFail
                                    };
                                    Server.SendViaProto(reply, c.conn, c.alg);
                                    //reply = new ProtoMessage {
                                    //    ActionType = Actions.Update,
                                    //    ResponseType = DisplayMessages.Error
                                    //};
                                    //Server.SendViaProto(reply, c.conn, c.alg);
                                    im.SenderConnection.Disconnect("Authentication Fail");
                                    Globals_Server.logEvent("Wrong Password, disconnecting user.");
                                }
                            }
                        }
                        // temp for testing, should validate connection first
                        else if (clientConnections.ContainsKey(im.SenderConnection))
                        {
                            if (Globals_Game.IsObserver(c))
                            {
                                ProcessMessage(m, im.SenderConnection);
                                ProtoClient clientDetails = new ProtoClient(c);
                                clientDetails.ActionType   = Actions.Update;
                                clientDetails.ResponseType = DisplayMessages.Success;
                                SendViaProto(clientDetails, im.SenderConnection, c.alg);
                            }
                            else
                            {
                                im.SenderConnection.Disconnect("Not logged in- Disconnecting");
                            }
                        }
                    }
                    break;

                    case NetIncomingMessageType.StatusChanged:
                        byte stat = im.ReadByte();
                        NetConnectionStatus status = NetConnectionStatus.None;
                        if (Enum.IsDefined(typeof(NetConnectionStatus), Convert.ToInt32(stat)))
                        {
                            status = (NetConnectionStatus)stat;
                        }
                        else
                        {
                            Globals_Server.logError("Failure to parse byte " + stat + " to NetConnectionStatus for endpoint " + im.ReadIPEndPoint());
                        }
                        Globals_Server.logEvent("\tStatus is now: " + status);
                        if (status == NetConnectionStatus.Disconnected)
                        {
                            string reason = im.ReadString();
                            if (reason == null)
                            {
                                reason = "Unknown";
                            }
                            Globals_Server.logEvent(im.SenderConnection.RemoteEndPoint.ToString() + " has disconnected. Reason: " + reason);
                            if (clientConnections.ContainsKey(im.SenderConnection))
                            {
                                Disconnect(im.SenderConnection);
                            }
                        }
                        break;

                    case NetIncomingMessageType.ConnectionApproval:
                    {
                        string senderID = im.ReadString();
                        string text     = im.ReadString();
                        Client client;
                        Globals_Server.Clients.TryGetValue(senderID, out client);
                        if (client != null)
                        {
                            ProtoLogIn logIn;
                            //ProtoMessage logIn;
                            if (!LogInManager.AcceptConnection(client, text, out logIn))
                            {
                                im.SenderConnection.Deny("User not recognised.");
                            }
                            else
                            {
                                ProtoMessage temp = logIn;

                                NetOutgoingMessage msg = server.CreateMessage();
                                MemoryStream       ms  = new MemoryStream();
                                // Include X509 certificate as bytes for client to validate
                                //Serializer.SerializeWithLengthPrefix<ProtoLogIn>(ms, logIn, PrefixStyle.Fixed32);
                                Serializer.SerializeWithLengthPrefix <ProtoMessage>(ms, temp, PrefixStyle.Fixed32);
                                msg.Write(ms.GetBuffer());

                                clientConnections.Add(im.SenderConnection, client);
                                client.conn = im.SenderConnection;
                                im.SenderConnection.Approve(msg);
                                //server.FlushSendQueue();
                                Globals_Server.logEvent("Accepted connection from " + client.username + " | " + senderID + " | " + text);
                            }
                        }
                        else
                        {
                            im.SenderConnection.Deny("Username unrecognised.");
                        }
                        server.FlushSendQueue();
                    }

                    break;

                    case NetIncomingMessageType.ConnectionLatencyUpdated:
                        Globals_Server.logEvent("LATENCY: Still getting these.");
                        break;

                    default:
                        Globals_Server.logError("Received unrecognised incoming message type: " + im.MessageType);
                        break;
                    }
                    server.Recycle(im);
                }
            }
            Globals_Server.logEvent("Server listening thread exits.");
        }
示例#22
0
 public MapFallbackTest(RoutingTestFixture <MapFallbackStartup> fixture)
 {
     _fixture = fixture;
     _client  = _fixture.CreateClient("http://localhost");
 }