static void Main(string[] args) { const int BufferSize = 8192; // 缓存大小,8192Bytes ConsoleKey key; Console.WriteLine("Server is running ... "); IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 }); TcpListener listener = new TcpListener(ip, 8500); listener.Start(); // 开始侦听 Console.WriteLine("Start Listening ..."); // 获取一个连接,中断方法 TcpClient remoteClient = listener.AcceptTcpClient(); // 打印连接到的客户端信息 Console.WriteLine("Client Connected!{0} <-- {1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint); // 获得流 NetworkStream streamToClient = remoteClient.GetStream(); RequestHandler handler = new RequestHandler(); do { // 写入buffer中 byte[] buffer = new byte[BufferSize]; int bytesRead; try { bytesRead = streamToClient.Read(buffer, 0, BufferSize); if (bytesRead == 0) throw new Exception("读取到0字节"); } catch (Exception ex) { Console.WriteLine(ex.Message); break; } Console.WriteLine("Reading data, {0} bytes ...", bytesRead); // 获得请求的字符串 string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead); string[] msgArray = handler.GetActualString(msg); foreach (string m in msgArray) { Console.WriteLine("Received: {0}", m); } } while (true); streamToClient.Dispose(); remoteClient.Close(); Console.WriteLine("\n\n输入\"Q\"键退出。"); do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); }
public RemoteClient(TcpClient client) { this.client = client; // 打印连接到的客户端信息; Console.WriteLine("\nClient Connected!{0} <-- {1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint); // 获得流; streamToClient = client.GetStream(); buffer = new byte[BufferSize]; // 设置RequestHandler; handler = new RequestHandler(); }
public RemoteClient(TcpClient client) { this.client = client; // 打印连接到的客户端信息 Console.WriteLine("\nClient Connected!{0} <-- {1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint); // 获得流 streamToClient = client.GetStream(); buffer = new byte[BufferSize]; // 设置RequestHandler handler = new RequestHandler(); // 在构造函数中就开始准备读取 AsyncCallback callBack = ReadComplete; streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null); }
public static void Test() { RequestHandler handler = new RequestHandler(); string input; // 第一种情况测试 - 一条消息完整发送 input = "[length=13]明天中秋,祝大家节日快乐!"; handler.PrintOutput(input); // 第二种情况测试 - 两条完整消息一次发送 input = "明天中秋,祝大家节日快乐!"; input = String.Format ("[length=13]{0}[length=13]{0}", input); handler.PrintOutput(input); // 第三种情况测试A - 两条消息不完整发送 input = "[length=13]明天中秋,祝大家节日快乐![length=13]明天中秋"; handler.PrintOutput(input); input = ",祝大家节日快乐!"; handler.PrintOutput(input); // 第三种情况测试B - 两条消息不完整发送 input = "[length=13]明天中秋,祝大家"; handler.PrintOutput(input); input = "节日快乐![length=13]明天中秋,祝大家节日快乐!"; handler.PrintOutput(input); // 第四种情况测试 - 元数据不完整 input = "[leng"; handler.PrintOutput(input); // 不会有输出 input = "th=13]明天中秋,祝大家节日快乐!"; handler.PrintOutput(input); }