心跳包实现
Posted 戈多编程
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了心跳包实现相关的知识,希望对你有一定的参考价值。
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("\n\n输入\"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("\n\n输入\"Q\"键退出。"); ConsoleKey key; do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); } }
以上是关于心跳包实现的主要内容,如果未能解决你的问题,请参考以下文章