心跳包實現
阿新 • • 發佈:2017-08-29
new exception work code byte oid sta line log
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); } }
心跳包實現