Пример #1
0
    //这个线程方法用来循环接收消息
    void ReceiveMessage()
    {
        while (true)
        {
            if (!clientSocket.Connected)
            {
                break;
            }
            int length = clientSocket.Receive(data);
            //message = Encoding.UTF8.GetString(data,0,length);

            if (length > 0)
            {
                TheMsg msg2 = ProtobufferTool.Deserialize <TheMsg>(data);
                message = $"{msg2.Name}说:{msg2.Content}";

                sw.Stop();
                //获取运行时间间隔
                TimeSpan ts = sw.Elapsed;
                //获取运行时间[毫秒]
                long times = sw.ElapsedMilliseconds;
                //获取运行的总时间
                long times2 = sw.ElapsedTicks;
                Debug.Log($"times={times} times2={times2}");
            }
        }
    }
Пример #2
0
        private void ReceiveMessage()
        {
            while (true)
            {
                //在接收数据时判断一下Socket是否端口连接
                if (clientSocket.Poll(10, SelectMode.SelectRead))
                {
                    clientSocket.Close(); //关闭当前连接
                    break;                //跳出循环,终止该线程执行
                }

                int length = clientSocket.Receive(data);
                //string message = Encoding.UTF8.GetString(data, 0, length); //ToDo: 接收到数据时,要把该数据分发到各个客户端
                //byte[] data = System.Text.Encoding.UTF8.GetBytes(message);

                //直接广播这个消息
                TCPServer.BroadcastMessage(data);

                if (length > 0)
                {
                    TheMsg msg2    = ProtobufferTool.Deserialize <TheMsg>(data);
                    string message = string.Format("{0}说: {1}", msg2.Name, msg2.Content);
                    Console.WriteLine("收到了消息:" + message + "[" + length + "]");
                }
            }
        }