Beispiel #1
0
        public void SendProtobufCmd(int serviceType, int cmdType, ProtoBuf.IExtensible body = null)
        {
            var cmdPackage = CmdPackageProtocol.PackageProtobuf(serviceType, cmdType, body);

            if (cmdPackage == null)
            {
                return;
            }
            var tcpPackage = TcpProtocol.Pack(cmdPackage);

            if (tcpPackage == null)
            {
                return;
            }

            try
            {
                this.clientSocket.BeginSend(
                    tcpPackage,
                    0,
                    tcpPackage.Length,
                    SocketFlags.None,
                    OnAfterSend, this.clientSocket);
            }
            catch (Exception e)
            {
                OnConnectError(e);
            }
        }
        public void Initialize()
        {
            ManualResetEventSlim mevent = new ManualResetEventSlim(false);

            ipv4Server      = new TcpProtocol();
            ipv4Server.Port = PORT;
            ipv4Server.OnConnectionRequested += (socket) =>
            {
                ipv4ServerClient = socket;
                mevent.Set();
            };
            ipv4Server.Address = serverAddress;
            ipv4Server.Listen();
            ipv6Server         = new TcpProtocol();
            ipv6Server.Port    = PORT;
            ipv6Server.Address = IPAddress.IPv6Any.ToString();
            mevent.Reset();
            ipv6Server.OnConnectionRequested += (socket) =>
            {
                ipv6ServerClient = socket;
                mevent.Set();
            };
            ipv6Server.Listen();
            ipv4Client = this.CreateIPV4ClientProtocol().Connect(serverAddress, PORT);
            mevent.Wait(1000);
            mevent.Reset();
            ipv6Client = this.CreateIPV6ClientProtocol().Connect(ipv6ServerAddress, PORT);
            mevent.Wait(1000);
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555));
                Console.WriteLine("连接服务器成功");
            }
            catch
            {
                Console.WriteLine("连接服务器失败");
                return;
            }

            string    sendstr  = "你好服务端";
            TcpBuffer sendPack = TcpProtocol.Pack(new TcpBuffer(Encoding.Default.GetBytes(sendstr)), 0);

            client.Send(sendPack.bytes);

            byte[] receiveBuffer = new byte[1000];
            client.Receive(receiveBuffer);
            TcpBuffer unpack = TcpProtocol.Unpack(new TcpBuffer(receiveBuffer));

            Console.WriteLine("服务端消息:" + unpack.ToString());
        }
        public void RunClient(object ipAddress)
        {
            client = new TcpClient(ipAddress.ToString(), 6969);

            while (true)
            {
                JObject received = TcpReadWrite.Read(client);
                string  command  = (string)received["command"];

                switch (command)
                {
                case "id":
                    form.Invoke(new Action(() => form.GetId(TcpProtocol.ReadId(received))));
                    break;

                case "questionScores":
                    form.Invoke(new Action(() => form.HandleQuestionsScores(TcpProtocol.QuestionAndScoreParse(received))));
                    break;

                case "endScores":
                    form.Invoke(new Action(() => form.HandleEndGame(TcpProtocol.EndScoresParse(received))));
                    client.GetStream().Close();
                    client.Close();
                    return;
                }
            }
        }
Beispiel #5
0
    public byte[] SendAndGetRespond(byte[] message)
    {
        Send(message);

        int counter = 0;
        var stream  = client.GetStream();

        while (counter < ResponseTimeout)
        {
            if (client.Available > 0)
            {
                int len = TcpProtocol.GetLength(stream);

                byte[] data = new byte[len];
                using (var received = new MemoryStream())
                {
                    int total = 0;
                    while (total < len)
                    {
                        byte[] buffer = new byte[client.Available];
                        int    read   = stream.Read(buffer, 0, buffer.Length);
                        received.Write(buffer, 0, read);
                        total += read;
                    }
                    data = received.GetBuffer();
                }

                return(data);
            }
            Thread.Sleep(1);
            counter++;
        }

        return(null);
    }
        public void StartGame()
        {
            logic = new GameLogic();

            gameData = new GameData(16);
            gameData.Snakes.Add(new Snake(new Point((int)(gameData.GridSize * 0.25), (int)(gameData.GridSize * 0.75)),
                                          Snake.Directions.Right, Color.ForestGreen, 1));
            gameData.Snakes.Add(new Snake(new Point((int)(gameData.GridSize * 0.75), (int)(gameData.GridSize * 0.25)),
                                          Snake.Directions.Left, Color.DeepSkyBlue, 2));
            logic.AddApples(gameData, amountOfApples);

            foreach (ClientHandler client in clients)
            {
                client.Write(TcpProtocol.IdSend(gameData, client.Id));
            }

            ReadAll(false);

            // Start timer that calls a game tick update
            timer          = new Timer();
            timer.Elapsed += OnTimedEvent;
            timer.Interval = 1000.0 / fps;

            RunGameOneTick();
            // Wait 3 seconds
            Thread.Sleep(3000);

            timer.Start();
        }
Beispiel #7
0
    private void Fork(string host, TcpClient client)
    {
        while (!stopListening && clients.ContainsKey(host))
        {
            if (client.Available >= 4)
            {
                var stream = client.GetStream();
                int len    = TcpProtocol.GetLength(stream); // Use binary formatter to auto proccess whole incomming data.

                byte[] data = new byte[len];
                using (var received = new MemoryStream())
                {
                    int total = 0;
                    while (total < len)
                    {
                        byte[] buffer = new byte[client.Available];
                        int    read   = stream.Read(buffer, 0, buffer.Length);
                        received.Write(buffer, 0, read);
                        total += read;
                    }
                    data = received.GetBuffer();
                }

                if (DataRecieved != null)
                {
                    DataRecieved(host, data);
                }
            }
        }
    }
Beispiel #8
0
        private bool CheckForPrevClient(TcpClient prevClient)
        {
            TcpHandler.WriteMessage(prevClient, TcpProtocol.CheckForDisconnectSend());

            int  waitTimeInMillis     = 500;
            bool noResponsePrevClient = false;

            long startTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

            while (prevClient.Available <= 0)
            {
                long currentTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
                if (currentTime - startTime >= waitTimeInMillis)
                {
                    noResponsePrevClient = true;
                    break;
                }
            }
            if (noResponsePrevClient)
            {
                return(false);
            }

            TcpHandler.ReadMessage(prevClient);
            return(true);
        }
Beispiel #9
0
 public void SendMessageToAll(byte[] message)
 {
     foreach (var client in clients.Values)
     {
         var framed = TcpProtocol.FrameMessage(message);
         client.NetInterface.Client.Send(framed);
     }
 }
        public void DisposeTest()
        {
            var ipv4Protocol = new TcpProtocol();

            ipv4Protocol.Port = 4884;
            ipv4Protocol.Listen();
            ipv4Protocol.Dispose();
            Assert.IsFalse(ipv4Protocol.Listening);
        }
 public void EndGame()
 {
     //Update de highscores en send de highscores
     foreach (ClientHandler client in clientHandlers)
     {
         gameLogic.GetScore(client.id);
         client.Write(TcpProtocol.EndScoresSend(gameLogic.GetScores()));
     }
 }
Beispiel #12
0
    private void OnPacketReceived(Buffer buffer, TcpProtocol source)
    {
        BinaryReader reader = buffer.BeginReading();

        reader.ReadByte();

        OnMessageReceived(reader.ReadString());

        buffer.Recycle();
    }
 public void Initialize()
 {
     ipv4Protocol = new TcpProtocol()
     {
         Port = PORT, Address = serverAddress
     };
     ipv6Protocol = new TcpProtocol()
     {
         Port = PORT, Address = IPAddress.IPv6Any.ToString()
     };
 }
        public void RunGameOneTick()
        {
            isRunning = true;

            // Ask all clients for their snakes' direction
            Broadcast(TcpProtocol.TickSend());

            // Read all client directions
            ReadAll(true);

            // Check if a client has been disconnected
            CheckIfDisconnected();

            // Logique
            // For each snake check if next move it eats an apple and then update the snake
            foreach (Snake snake in GetAliveSnakes())
            {
                bool hasEaten = false;
                for (int i = gameData.Apples.Count - 1; i >= 0; i--)
                {
                    if (logic.EatsAnApple(snake, gameData.Apples[i]))
                    {
                        gameData.Apples.Remove(gameData.Apples[i]);
                        hasEaten = true;
                        break;
                    }
                }
                snake.UpdateBody(hasEaten);
            }

            // For each snake check if it's dead
            foreach (Snake snake in GetAliveSnakes())
            {
                if (logic.CheckForDeath(GetAliveSnakes(), snake, gameData.GridSize))
                {
                    snake.IsDead = true;
                }
            }

            // Add the apples back that have been eaten
            logic.AddApples(gameData, amountOfApples);

            // Send updated gameData to the clients
            Broadcast(TcpProtocol.DataSend(gameData));

            // Check for end game
            if (GameHasEnded())
            {
                EndGame();
                return;
            }

            isRunning = false;
        }
Beispiel #15
0
        public void Connect()
        {
            clientSocket.Connect(address, port);

            protocol = new TcpProtocol(clientSocket);

            protocol.OnClose += Protocol_OnClose;
            protocol.OnData  += Protocol_OnData;

            protocol.Reader();
            Connected?.Invoke(this);
        }
Beispiel #16
0
        public void TcpProtocolMethodSyncTest()
        {
            //Arrange
            var         log     = new Mock <ILogger>();
            TcpProtocol protocl = new TcpProtocol();
            //Act
            var result = protocl.SendRequestAsync(log.Object).Result;

            //Assert
            Assert.IsNotNull(result);
            Assert.IsFalse(result.GetStatus);
        }
Beispiel #17
0
        private void btnPing_Click(object sender, EventArgs e)
        {
            IProtocol protocol = new TcpProtocol(tbOtherPeerUrl.Text, tbOtherPeerPort.Text.to_i());
            RpcError  err      = protocol.Ping(dht.Contact);

            if (err.HasError)
            {
                MessageBox.Show("Peer error: " + err.PeerErrorMessage + "\r\n" +
                                "Protocol error: " + err.ProtocolErrorMessage + "\r\n" +
                                "Timeout: " + err.TimeoutError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private Task ReadClientDirection(ClientHandler client)
        {
            JObject jObject = client.Read();

            lock (client)
            {
                Snake snake = GetSnake(client.Id);
                snake.Direction         = TcpProtocol.DirectionReceived(jObject);
                snake.PreviousDirection = snake.Direction;
            }
            return(Task.FromResult <object>(null));
        }
Beispiel #19
0
    public void Send(byte[] message)
    {
        if (!client.Connected)
        {
            client.Connect(server);
        }

        byte[] data = TcpProtocol.FrameMessage(message);

        var stream = client.GetStream();

        stream.Write(data, 0, data.Length);
    }
Beispiel #20
0
    public void SendMessage(string host, byte[] message)
    {
        if (!clients.ContainsKey(host))
        {
            throw new InvalidOperationException(string.Format("No such host ({0}) is connected to the server.", host));
        }

        var framed = TcpProtocol.FrameMessage(message);

        var client = clients[host];

        client.NetInterface.Client.Send(framed);
    }
 public void ConnectIPV6Test()
 {
     try
     {
         ipv6Protocol.Listen();
         TcpProtocol ipvClient = this.CreateIPV6ClientProtocol();
         var         socket    = ipvClient.Connect(ipv6ServerAddress, PORT);
         Assert.IsTrue(socket.Connected, "A connection could not be established.");
     }
     catch (Exception ex)
     {
         Assert.Fail(ex.ToString());
     }
 }
Beispiel #22
0
        public async Task TcpProtocolMethodASyncTestAsync()
        {
            //Arrange
            var         log      = new Mock <ILogger>();
            TcpProtocol protocol = new TcpProtocol()
            {
                HostName = "8.8.8.8", Port = 111
            };

            //Act
            var result = await protocol.SendRequestAsync(log.Object);

            //Assert
            Assert.IsNotNull(result);
            Assert.IsFalse(result.GetStatus);
        }
        public async Task ConnectAsyncIPV6TaskTest()
        {
            try
            {
                ipv6Protocol.Listen();
                TcpProtocol ipvClient = this.CreateIPV6ClientProtocol();
                var         tcpSocket = await ipvClient.ConnectAsync(ipv6ServerAddress, PORT);

                Assert.IsNotNull(tcpSocket);
                Assert.IsTrue(tcpSocket.Connected);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.ToString());
            }
        }
        public void StartGame()
        {
            // Intis
            int players = clientHandlers.Count;

            form.gameStarted = true;
            form.SetGameStarted();
            gameLogic = new GameLogic(questions, ids);

            foreach (ClientHandler client in clientHandlers)
            {
                client.Write(TcpProtocol.SendId(client.id));
            }

            // Start the game loop
            while (true)
            {
                var currentQuestion = gameLogic.NextQuestion();
                if (currentQuestion == null)
                {
                    EndGame();
                    form.gameStarted = false;
                    form.SetGameStarted();
                    return;
                }

                // Send out the question + scores to the clients
                Broadcast(TcpProtocol.QuestionScoresSend(currentQuestion, gameLogic.GetScores()));

                // Wait for all clients to be finished (in threads)
                int finishedClients = 0;
                while (finishedClients != players)
                {
                    foreach (ClientHandler client in clientHandlers)
                    {
                        int playerTime = TcpProtocol.TimeParse(client.Read());
                        gameLogic.AddToScore(client.id, playerTime);
                        finishedClients++;

                        //for debugging
                        Console.WriteLine(@"Playertime: " + playerTime);
                        Console.WriteLine(@"PlayerID: " + client.id + @"Score: " + gameLogic.GetScore(client.id));
                    }
                    Thread.Sleep(1);
                }
            }
        }
Beispiel #25
0
            /// <summary>
            /// 处理接收到的客户端数据
            /// </summary>
            private void ProcessReceive()
            {
                if (m_readWriteEventArg.BytesTransferred > 0 &&
                    m_readWriteEventArg.SocketError == SocketError.Success)
                {
                    // 处理接收到的数据
                    m_receiveBuffer.count = m_readWriteEventArg.BytesTransferred;
                    TcpBuffer receivePack = TcpProtocol.Unpack(m_receiveBuffer);
                    if (receivePack == null)
                    {
                        Console.WriteLine("接收客户端数据错误");
                        Close();
                        return;
                    }

                    Console.WriteLine("接收到客户端数据:" + receivePack.ToString());

                    // 填充发送缓冲区
                    string    sendStr    = "客户端你好";
                    TcpBuffer sendPack   = new TcpBuffer(Encoding.Default.GetBytes(sendStr));
                    TcpBuffer sendBuffer = TcpProtocol.Pack(sendPack, 0);
                    if (sendBuffer == null)
                    {
                        Console.WriteLine("数据处理错误");
                        Close();
                        return;
                    }

                    System.Buffer.BlockCopy(sendBuffer.bytes, sendBuffer.offset, m_sendBuffer.bytes, m_sendBuffer.offset, sendBuffer.count);
                    m_sendBuffer.count = sendBuffer.count;

                    // 设置发送缓冲区
                    m_readWriteEventArg.SetBuffer(m_sendBuffer.bytes, m_sendBuffer.offset, m_sendBuffer.count);

                    // 异步发送
                    bool willRaiseEvent = m_socket.SendAsync(m_readWriteEventArg);
                    if (!willRaiseEvent)
                    {
                        ProcessSend();
                    }
                }
                else
                {
                    Close();
                }
            }
        public void OnConnectionRequestedTest()
        {
            ManualResetEventSlim mevent = new ManualResetEventSlim(false);

            ipv4Protocol.Listen();
            mevent.Reset();
            bool eventInvoked = false;

            ipv4Protocol.OnConnectionRequested += (socket) =>
            {
                eventInvoked = true;
                mevent.Set();
            };
            TcpProtocol ipvClient    = this.CreateIPV4ClientProtocol();
            var         clientSocket = ipvClient.Connect(serverAddress, PORT);

            mevent.Wait(10000);
            Assert.IsTrue(eventInvoked);
        }
Beispiel #27
0
        public void TcpProtocolTest()
        {
            //Arrange
            var    mock         = new Mock <TcpProtocol>("192.168.7.29:980");
            var    ilog         = new Mock <ILogger>();
            string expectedHost = "192.168.7.29";
            int    expectedPort = 980;
            var    mock2        = new Mock <TcpProtocol>("10.200.224.201:5050"); //localhost

            //Act
            TcpProtocol protocol  = mock.Object;
            TcpProtocol protocol2 = mock2.Object;

            //Assert
            Assert.AreEqual(expectedHost, protocol.Host);
            Assert.AreEqual(expectedPort, protocol.Port);
            Assert.IsNotNull(protocol.Message);
            Assert.IsNotNull(protocol.ProtocolName);
            Assert.IsFalse(protocol.SendRequest(ilog.Object).IsSucces);
            Assert.IsFalse(protocol2.SendRequest(ilog.Object).IsSucces); //порт закрыт :(
        }
        public void ConnectAsyncIPV6CallbackTest()
        {
            ManualResetEventSlim mevent = new ManualResetEventSlim(false);

            mevent.Reset();
            try
            {
                ipv6Protocol.Listen();
                TcpProtocol ipvClient = this.CreateIPV6ClientProtocol();
                ipvClient.ConnectAsync((socket) =>
                {
                    Assert.IsTrue(socket.Connected, "A connection could not be established.");
                    mevent.Set();
                }, ipv6ServerAddress, PORT);
                mevent.Wait(10000);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.ToString());
            }
        }
Beispiel #29
0
        public void SendJsonCmd(int serviceType, int cmdType, string jsonStr)
        {
            var cmdPackage = CmdPackageProtocol.PackageJson(serviceType, cmdType, jsonStr);

            if (cmdPackage == null)
            {
                return;
            }
            var tcpPackage = TcpProtocol.Pack(cmdPackage);

            if (tcpPackage == null)
            {
                return;
            }

            this.clientSocket.BeginSend(
                tcpPackage,
                0,
                tcpPackage.Length,
                SocketFlags.None,
                OnAfterSend, this.clientSocket);
        }
        public void EndGame()
        {
            // Stop the game timer
            timer.Stop();

            // Get previous highscores
            Highscore highscore = Highscore.ReadHighScores();

            // Update highscores
            foreach (ClientHandler client in clients)
            {
                highscore.AddHighScore(GetSnake(client.Id).Body.Count, client.Name);
            }
            highscore.WriteHighScores();

            // Send Endpacket and highscores
            Broadcast(TcpProtocol.EndSend());
            foreach (ClientHandler client in clients)
            {
                client.Write(TcpProtocol.HighscoreSend(highscore));
            }
        }