Ejemplo n.º 1
0
        //服务端处理
        private static void clientConnected(IAsyncResult result)
        {
            try
            {
                TcpListener server = (TcpListener)result.AsyncState;
                using (TcpClient client = server.EndAcceptTcpClient(result))
                {
                    using (NetworkStream stream = client.GetStream())
                    {
                        //获取
                        Console.WriteLine("SERVER : 客户端已连接,数据读取中 --- ");
                        byte[] myRequestBuffer = new byte[49];
                        int    myRequestLength = 0;
                        do
                        {
                            myRequestLength = stream.Read(myRequestBuffer, 0, myRequestBuffer.Length);
                        }while (stream.DataAvailable);
                        MyRequest myRequest = MyRequest.ParseFrom(myRequestBuffer);
                        MyData    myData    = MyData.ParseFrom(myRequest.Data);
                        Console.WriteLine("SERVER : 获取成功, myRequest.Version={0}, myRequest.Name={1}, myRequest.Website={2}, myData.Resume={3}", myRequest.Version, myRequest.Name, myRequest.Website, myData.Resume);

                        //响应(MyResponse)
                        MyResponse.Builder myResponseBuilder = MyResponse.CreateBuilder();
                        myResponseBuilder.Version = myRequest.Version;
                        myResponseBuilder.Result  = 99;
                        MyResponse myResponse = myResponseBuilder.Build();
                        myResponse.WriteTo(stream);
                        Console.WriteLine("SERVER : 响应成功 ---");

                        Console.WriteLine("SERVER: 关闭连接 ---");
                        stream.Close();
                    }
                    client.Close();
                }
            }
            finally
            {
                allDone.Set();
            }
        }