コード例 #1
0
ファイル: Program.cs プロジェクト: yaserOSource/KingNetwork
        /// <summary>
        /// Method responsible for execute the callback of on client connected handler.
        /// </summary>
        /// <param name="client">The client instance.</param>
        private void OnClientConnectedHandler(IClient client)
        {
            try
            {
                Console.WriteLine($"OnClientConnected: {client.Id}");

                using (var kingBuffer = KingBufferWriter.Create())
                {
                    kingBuffer.Write(MyPackets.PlayerPositionsArray);
                    kingBuffer.Write(_networkPlayersDictionary.Count);

                    foreach (var player in _networkPlayersDictionary)
                    {
                        kingBuffer.Write(player.Key.Id);

                        kingBuffer.Write(player.Value.X);
                        kingBuffer.Write(player.Value.Y);
                        kingBuffer.Write(player.Value.Z);
                    }

                    _server.SendMessage(client, kingBuffer);

                    if (!_networkPlayersDictionary.ContainsKey(client))
                    {
                        _networkPlayersDictionary.Add(client, new NetworkPlayer(client));
                    }

                    _networkPlayersDictionary[client].Moved = true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}.");
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: yaserOSource/KingNetwork
        /// <summary>
        /// This method is responsible for sychronize the players positions.
        /// </summary>
        public void SynchronizePlayersPositions()
        {
            try
            {
                var sendPosDict = new Dictionary <IClient, NetworkPlayer>(_networkPlayersDictionary);

                foreach (var sendToPlayer in sendPosDict)
                {
                    if (sendToPlayer.Value == null)
                    {
                        continue;
                    }

                    using (var kingBuffer = KingBufferWriter.Create())
                    {
                        kingBuffer.Write(MyPackets.PlayerPositionsArray);
                        kingBuffer.Write(sendPosDict.Count(c => c.Key.Id != sendToPlayer.Key.Id && c.Value.Moved));

                        int amountPlayersMoved = 0;

                        foreach (var posPlayers in sendPosDict)
                        {
                            if (sendToPlayer.Key.Id == posPlayers.Key.Id)
                            {
                                continue;
                            }

                            if (!posPlayers.Value.Moved)
                            {
                                continue;
                            }

                            kingBuffer.Write(posPlayers.Key.Id);

                            kingBuffer.Write(posPlayers.Value.X);
                            kingBuffer.Write(posPlayers.Value.Y);
                            kingBuffer.Write(posPlayers.Value.Z);

                            amountPlayersMoved++;
                        }

                        if (amountPlayersMoved > 0)
                        {
                            _server.SendMessage(sendToPlayer.Key, kingBuffer);
                        }
                    }
                }

                foreach (var player in _networkPlayersDictionary)
                {
                    player.Value.Moved = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
コード例 #3
0
        /// <summary>
        /// The callback from received message from connected server.
        /// </summary>
        /// <param name="asyncResult">The async result from a received message from connected server.</param>
        private void ReceiveDataCallback(IAsyncResult asyncResult)
        {
            EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);

            int num;

            try
            {
                num = _listener.EndReceiveFrom(asyncResult, ref endPoint);
            }
            catch (SocketException)
            {
                _listener.BeginReceiveFrom((byte[])asyncResult.AsyncState, 0, _maxMessageBuffer, SocketFlags.None, ref endPoint, new AsyncCallback(this.ReceiveDataCallback), (byte[])asyncResult.AsyncState);
                return;
            }

            byte[] array = new byte[num];
            Buffer.BlockCopy((byte[])asyncResult.AsyncState, 0, array, 0, num);

            _listener.BeginReceiveFrom((byte[])asyncResult.AsyncState, 0, _maxMessageBuffer, SocketFlags.None, ref endPoint, new AsyncCallback(this.ReceiveDataCallback), (byte[])asyncResult.AsyncState);

            var kingUdpClientsObj = _kingUdpClients;

            Monitor.Enter(kingUdpClientsObj);

            bool      hasClientConnection = false;
            UDPClient kingUdpClient       = null;

            try
            {
                hasClientConnection = _kingUdpClients.TryGetValue(endPoint, out kingUdpClient);
            }
            finally
            {
                Monitor.Exit(kingUdpClientsObj);
            }

            if (hasClientConnection)
            {
                kingUdpClient.ReceiveDataCallback(array);
            }
            else if (array.Length == 9)
            {
                var clientId = GetNewClientIdentifier();
                var client   = new UDPClient(clientId, this, endPoint, _messageReceivedHandler, _clientDisconnectedHandler, _maxMessageBuffer);

                _kingUdpClients.Add(endPoint, client);

                var writter = KingBufferWriter.Create();
                writter.Write((byte)1);

                client.SendMessage(writter);

                _clientConnectedHandler(client);
            }
        }
コード例 #4
0
 /// <summary>
 /// Method responsible for send message to specific connected client.
 /// </summary>
 /// <param name="client">The client instance.</param>
 /// <param name="kingBuffer">The king buffer of received message.</param>
 public void SendMessage(IClient client, KingBufferWriter kingBuffer)
 {
     try
     {
         client.SendMessage(kingBuffer);
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Error: {ex.Message}.");
     }
 }
コード例 #5
0
        /// <summary>
        /// This method is reponsible for wait for connections.
        /// </summary>
        private async void WaitConnection()
        {
            while (_webSocket.State == WebSocketState.Open)
            {
                try
                {
                    var ret = await _webSocket.ReceiveAsync(_buff, CancellationToken.None);

                    if (ret.MessageType == WebSocketMessageType.Text)
                    {
                        if (_listenerContext.Request.RemoteEndPoint != null)
                        {
                            var data = _buff.Take(ret.Count).ToArray();

                            var writer = KingBufferWriter.Create();
                            writer.Write(data);

                            var reader = KingBufferReader.Create(writer.BufferData, 0, writer.Length);

                            _messageReceivedHandler(this, reader);
                        }
                    }
                    else if (ret.MessageType == WebSocketMessageType.Binary)
                    {
                        if (_listenerContext.Request.RemoteEndPoint != null)
                        {
                            var reader = KingBufferReader.Create(_buff.Take(ret.Count).ToArray(), 0, ret.Count);
                            _messageReceivedHandler(this, reader);
                        }
                    }
                    else if (ret.MessageType == WebSocketMessageType.Close)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (_webSocket.State != WebSocketState.Open)
                    {
                        _clientDisconnectedHandler(this);
                        Console.WriteLine($"Client '{IpAddress}' Disconnected.");
                    }
                    else
                    {
                        Console.WriteLine($"Error: {ex.Message}.");
                    }
                    break;
                }
            }
        }
コード例 #6
0
 /// <summary>
 /// Method responsible for send message to all connected client minus one specific client.
 /// </summary>
 /// <param name="client">The client instance.</param>
 /// <param name="kingBuffer">The king buffer of received message.</param>
 public void SendMessageToAllMinus(IClient client, KingBufferWriter kingBuffer)
 {
     try
     {
         foreach (var clientToSend in GetAllClients().Where(c => c.IsConnected && c.Id != client.Id))
         {
             SendMessage(clientToSend, kingBuffer);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Error: {ex.Message}.");
     }
 }
コード例 #7
0
 /// <summary>
 /// Method responsible for execute the callback of on message received handler.
 /// </summary>
 /// <param name="client">The client instance.</param>
 /// <param name="reader">The king buffer reader from received message.</param>
 private void OnMessageReceived(IClient client, IKingBufferReader reader)
 {
     try
     {
         switch (reader.ReadMessagePacket <MyPackets>())
         {
         case MyPackets.Message:
             Console.WriteLine($"Received message: {reader.ReadString()}.");
             _server.SendMessageToAllMinus(client, KingBufferWriter.Create());
             break;
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Error: {ex.Message}.");
     }
 }
コード例 #8
0
ファイル: Program.cs プロジェクト: yaserOSource/KingNetwork
        private static void OnClientConnectedHandler(IClient client)
        {
            try
            {
                Console.WriteLine($"OnClientConnectedHandler from {client.IpAddress}");

                var writer = KingBufferWriter.Create();

                writer.Write("Testinho2");

                client.SendMessage(writer);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}.");
            }
        }
コード例 #9
0
        /// <summary>
        /// Method responsible for starts the web socket connection.
        /// </summary>
        /// <param name="uri">The uri to start the connection</param>
        public async void StartConnection(Uri uri)
        {
            try
            {
                if (_clientWebSocket.State == WebSocketState.Open)
                {
                    return;
                }
                await _clientWebSocket.ConnectAsync(uri, CancellationToken.None);

                while (IsConnected)
                {
                    var ret = await _clientWebSocket.ReceiveAsync(_buff, CancellationToken.None);

                    if (ret.MessageType == WebSocketMessageType.Text)
                    {
                        var data = _buff.Take(ret.Count).ToArray();

                        var writer = KingBufferWriter.Create();
                        writer.Write(data);

                        var reader = KingBufferReader.Create(writer.BufferData, 0, writer.Length);

                        _messageReceivedHandler(reader);
                    }
                    else if (ret.MessageType == WebSocketMessageType.Binary)
                    {
                        var reader = KingBufferReader.Create(_buff.Take(ret.Count).ToArray(), 0, ret.Count);
                        _messageReceivedHandler(reader);
                    }
                }
            }
            catch (Exception ex)
            {
                if (IsConnected)
                {
                    _disconnectedHandler();
                }
                else
                {
                    Console.WriteLine($"Error: {ex.Message}.");
                }
            }
        }
コード例 #10
0
        public void Verify_KingTCPClientMessageReceivedHandler_ShouldHasReceivedMessage()
        {
            bool hasMessageReceived = false;

            _kingClient.MessageReceivedHandler += (IKingBufferReader reader) =>
            {
                hasMessageReceived = true;
            };

            var writer = KingBufferWriter.Create();

            writer.Write("Test Message");

            _kingServer.SendMessageToAll(writer);

            Thread.Sleep(15);

            Assert.True(hasMessageReceived);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: yaserOSource/KingNetwork
        /// <summary>
        /// Method responsible for execute the callback of message received from client in server.
        /// </summary>
        /// <param name="client">The client instance.</param>
        /// <param name="reader">The king buffer reader from received message.</param>
        private static void OnMessageReceived(IClient client, IKingBufferReader reader)
        {
            try
            {
                if (_networkListenerType == NetworkListenerType.WSText)
                {
                    Console.WriteLine($"OnMessageReceived from {client.Id}");

                    string text = reader.ReadString();
                    Console.WriteLine($"Message: {text}");

                    var writer = KingBufferWriter.Create();

                    writer.Write("Testinho2");

                    client.SendMessage(writer);
                }
                else
                {
                    switch (reader.ReadMessagePacket <MyPackets>())
                    {
                    case MyPackets.PacketOne:
                        Console.WriteLine($"OnMessageReceived PacketOne from {client.Id}");
                        Console.WriteLine($"Message: {reader.ReadString()}");

                        var writer = KingBufferWriter.Create();

                        writer.Write(MyPackets.PacketOne);
                        writer.Write("Testinho2");

                        client.SendMessage(writer);

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}.");
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: yaserOSource/KingNetwork
        /// <summary>
        /// This method is responsible for main execution of console application.
        /// </summary>
        /// <param name="args">The string args received by parameters.</param>
        static void Main(string[] args)
        {
            try
            {
                _networkListenerType = NetworkListenerType.UDP;

                var client = new KingClient();
                client.MessageReceivedHandler = OnMessageReceived;
                client.Connect("127.0.0.1", 7171, _networkListenerType);

                if (client.HasConnected)
                {
                    Console.WriteLine("client.HasConnected");
                }

                new Thread(() =>
                {
                    Thread.Sleep(5000);

                    using (var buffer = KingBufferWriter.Create())
                    {
                        if (_networkListenerType != NetworkListenerType.WSText)
                        {
                            buffer.Write(MyPackets.PacketOne);
                        }

                        buffer.Write("Testinho1");

                        client.SendMessage(buffer);
                    }
                }).Start();

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
コード例 #13
0
ファイル: Network.cs プロジェクト: yaserOSource/KingNetwork
    private void Update()
    {
        if (client != null && client.HasConnected)
        {
            lastDistance = Vector3.Distance(lastNetworkedPosition, player.transform.position);
            if (lastDistance >= MIN_DISTANCE_TO_SEND_POSITION)
            {
                using (var kingBuffer = KingBufferWriter.Create())
                {
                    kingBuffer.Write(MyPackets.PlayerPosition);
                    kingBuffer.Write(player.transform.position.x);
                    kingBuffer.Write(player.transform.position.y);
                    kingBuffer.Write(player.transform.position.z);

                    client.SendMessage(kingBuffer);

                    lastNetworkedPosition = player.transform.position;
                }
            }
        }

        if (netPlayersDictionary != null)
        {
            foreach (var player in netPlayersDictionary)
            {
                if (!player.Value.GameObjectAdded)
                {
                    player.Value.GameObjectAdded = true;
                    player.Value.GameObject      = Instantiate(netPlayerPrefab, player.Value.Position, Quaternion.identity);
                }
                else
                {
                    player.Value.GameObject.transform.position = player.Value.Position;
                }
            }
        }
    }
コード例 #14
0
        /// <summary>
        /// Method responsible for execute the callback of message received from client in server.
        /// </summary>
        /// <param name="client">The client instance.</param>
        /// <param name="kingBuffer">The king buffer from received message.</param>
        private static void OnMessageReceived(IClient client, IKingBufferReader reader)
        {
            try
            {
                if (_networkListenerType == NetworkListenerType.WSText)
                {
                    Console.WriteLine($"OnMessageReceived: {reader.ReadString()}");
                }
                else
                {
                    var buffer = KingBufferWriter.Create();
                    buffer.Write(reader.ReadString());

                    _server.SendMessage(client, buffer);

                    _messagesReceived++;
                    _dataReceived += reader.Length;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}.");
            }
        }
コード例 #15
0
        /// <summary>
        /// Method responsible for start the clients.
        /// </summary>
        /// <param name="ip">The ip address from the server.</param>
        /// <param name="clientConnections">The number of client connections.</param>
        public static void StartClients(string ip, int clientConnections)
        {
            _networkListenerType = NetworkListenerType.WSBinary;

            var kingBuffer = KingBufferWriter.Create();

            //kingBuffer.Write((byte)0);
            kingBuffer.Write("Sometimes we just need a good networking library");

            _stopwatch = Stopwatch.StartNew();

            var clientFrequency = 14;

            var clients = new List <KingClient>();

            for (int i = 0; i < clientConnections; ++i)
            {
                var client = new KingClient();

                client.MessageReceivedHandler = OnMessageReceived;

                client.Connect(ip, 7171, _networkListenerType);
                clients.Add(client);

                Thread.Sleep(15);
            }

            Console.WriteLine("started all clients");

            new Thread(() =>
            {
                Thread.Sleep(10000);

                foreach (var client in clients)
                {
                    //if (client.HasConnected)
                    //{
                    // send 2 messages each time

                    var bytes = Encoding.GetEncoding("UTF-8").GetBytes("Testinho");

                    kingBuffer.Reset();

                    kingBuffer.Write(bytes);

                    client.SendMessage(kingBuffer);
                    //client.SendMessage(kingBuffer);

                    _messagesSent += 1;
                    //}
                }
            }).Start();

            //foreach (var client in clients)
            //{
            //    if (client.HasConnected)
            //    {
            //        // send 2 messages each time
            //        client.SendMessage(kingBuffer);
            //        //client.SendMessage(kingBuffer);

            //        _messagesSent += 1;
            //    }
            //}

            var timer = new System.Timers.Timer(1000.0 / clientFrequency);

            timer.Elapsed += (object sender, ElapsedEventArgs e) =>
            {
                //foreach (var client in clients)
                //{
                //    if (client.HasConnected)
                //    {
                //        // send 2 messages each time
                //        client.SendMessage(kingBuffer);
                //        //client.SendMessage(kingBuffer);

                //        _messagesSent += 1;
                //    }
                //}

                //// report every 10 seconds
                //if (_stopwatch.ElapsedMilliseconds > 1000 * 10)
                //{
                //    long bandwithIn = _dataReceived * 1000 / (_stopwatch.ElapsedMilliseconds * 1024);
                //    long bandwithOut = _messagesSent * _bufferLength * 1000 / (_stopwatch.ElapsedMilliseconds * 1024);

                //    Console.WriteLine(string.Format("Client in={0} ({1} KB/s)  out={2} ({3} KB/s) bufferL={4}",
                //                             _messagesReceived,
                //                             bandwithIn,
                //                             _messagesSent,
                //                             bandwithOut,
                //                             _bufferLength));
                //    _stopwatch.Stop();
                //    _stopwatch = Stopwatch.StartNew();
                //    _messagesSent = 0;
                //    _dataReceived = 0;
                //    _messagesReceived = 0;
                //}
            };

            timer.AutoReset = true;
            timer.Enabled   = true;

            Console.ReadLine();
            timer.Stop();
            timer.Dispose();
        }