.net 基于TCP的通信

 

服务端:

            TcpListener listener = new TcpListener(IPAddress.Any, 1112);//端口号1112
            listener.Start(12);
            while (true)
            {
                try
                {
                    Socket s = listener.AcceptSocket();
                    byte[] recByte = new byte[40960000];
                    int bytes = s.Receive(recByte, recByte.Length, 0);
                    var recStr = Encoding.UTF8.GetString(recByte, 0, bytes);
                    byte[] res = new byte[0];

                    if (recStr == "query")//如果接收一个请求
                    {
                        res = System.Text.Encoding.UTF8.GetBytes("成功啦!");

                        s.Send(res);//发送
                        s.Shutdown(SocketShutdown.Send);
                    }
                }
                catch (Exception ex)
                {

                    throw;
                }
            }

 

客户端:

            using (TcpClient client = new TcpClient())
            {
                client.Connect("localhost", 1112);//端口号1112
                using (NetworkStream stream = client.GetStream())
                {
                    byte[] data = Encoding.UTF8.GetBytes("query");
                    stream.Write(data, 0, data.Length); //1.这里是写入需要传递给服务端的数据,第一个参数是传入的字符数组,第二个是从哪个开始的偏移量,第三个是写入的数据大小长度
                    byte[] recByte = new byte[40960000];
                    var bytes = stream.Read(recByte, 0, recByte.Length);
                    string recStr = Encoding.UTF8.GetString(recByte, 0, bytes);
                    var result22 = recStr.Replace("\n", "<br/>");
                }
            }

 

posted @ 2019-07-09 14:23  小确幸123  阅读(1842)  评论(0编辑  收藏  举报