心跳包实现

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("客务端");
            TcpClient cline;
            // 与服务器连接
            try
            {
                cline = new TcpClient();
                cline.Connect("localhost", 8800);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                return;
            }

            string msg = ""其实我在潜水,请不要抛弃我"";
            //发往服务器
            NetworkStream streamToServer = cline.GetStream();
            byte[] BString = Encoding.Unicode.GetBytes(msg);
         
            streamToServer.Write(BString, 0, BString.Length);
            Console.WriteLine("发送:{0}", msg);
            //退出Q
            Console.WriteLine("

输入"Q"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
        }
    }

  

class Program
    {
        static void Main(string[] args)
        {
            const int BSize = 8192;
            Console.WriteLine("服务端");
            //设ip和端口
            IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            TcpListener list = new TcpListener(ip, 8800);

            list.Start();  //开始侦听
            Console.WriteLine("开始侦听");
            TcpClient TC = list.AcceptTcpClient();
            // 获得流
            NetworkStream NS = TC.GetStream();
            byte[] BString = new byte[BSize];
            int bytesRead = NS.Read(BString, 0, BSize);
            Console.WriteLine("字节:{0} bytes ...", bytesRead);
            // 获得请求的字符串
            string msg = Encoding.Unicode.GetString(BString, 0, bytesRead);
            Console.WriteLine("收到:{0}", msg);
            //退出Q
            Console.WriteLine("

输入"Q"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } 
            while (key != ConsoleKey.Q);
        }
    }

  

原文地址:https://www.cnblogs.com/geduocoding/p/7449179.html