Example #1
0
        //客户端请求
        private static void runClient(object state)
        {
            try
            {
                //构造MyData
                MyData.Builder myDataBuilder = MyData.CreateBuilder();
                myDataBuilder.Resume = "我的个人简介";
                MyData myData = myDataBuilder.Build();

                //构造MyRequest
                MyRequest.Builder myRequestBuilder = MyRequest.CreateBuilder();
                myRequestBuilder.Version = 1;
                myRequestBuilder.Name    = "吴剑";
                myRequestBuilder.Website = "www.paotiao.com";
                //注:直接支持ByteString类型
                myRequestBuilder.Data = myData.ToByteString();
                MyRequest myRequest = myRequestBuilder.Build();

                Console.WriteLine("CLIENT : 对象构造完毕 ...");

                using (TcpClient client = new TcpClient())
                {
                    client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9528));
                    Console.WriteLine("CLIENT : socket 连接成功 ...");

                    using (NetworkStream stream = client.GetStream())
                    {
                        //发送
                        Console.WriteLine("CLIENT : 发送数据 ...");
                        myRequest.WriteTo(stream);

                        //接收
                        Console.WriteLine("CLIENT : 等待响应 ...");
                        byte[] myResponseBuffer = new byte[4];
                        int    myResponseLength = 0;
                        do
                        {
                            myResponseLength = stream.Read(myResponseBuffer, 0, myResponseBuffer.Length);
                        }while (stream.DataAvailable);
                        MyResponse myResponse = MyResponse.ParseFrom(myResponseBuffer);
                        Console.WriteLine("CLIENT : 成功获取结果, myResponse.Version={0}, myResponse.Result={1}", myResponse.Version, myResponse.Result);

                        //关闭
                        stream.Close();
                    }
                    client.Close();
                    Console.WriteLine("CLIENT : 关闭 ...");
                }
            }
            catch (Exception error)
            {
                Console.WriteLine("CLIENT ERROR : {0}", error.ToString());
            }
        }