测试TestTcp请求----处理Socket,代码如下:
#region 测试TestTcp测试Socket /// <summary> /// 测试TestTcp /// </summary> public static void TestTcpSocket() { var threadStart = new Thread(new ThreadStart(StartTestTcpSocket)) { IsBackground = true }; threadStart.Start(); Console.WriteLine($"TestTcp开始测试数据"); int test = 1; while (true) { #region TcpClient //TcpClient tcpClient = new TcpClient(); //tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 1122); //Console.WriteLine($"TcpClient 发送数据:{test}"); //await tcpClient.GetStream().WriteAsync(Encoding.UTF8.GetBytes($"client{test}")); //var buffer = new byte[1024]; //var socketConnReceCount = await tcpClient.GetStream().ReadAsync(buffer, 0, buffer.Length); //Console.WriteLine($"TcpClient 接收数据:{Encoding.UTF8.GetString(buffer, 0, socketConnReceCount)}"); //test++; //Thread.Sleep(2000); //tcpClient.Dispose(); #endregion #region Socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1122)); Console.WriteLine($"socket client 发送数据:{test}"); socket.Send(Encoding.UTF8.GetBytes($"client{test}")); var buffer = new byte[1024]; var socketConnReceCount = socket.Receive(buffer); Console.WriteLine($"socket client 接收数据:{Encoding.UTF8.GetString(buffer, 0, socketConnReceCount)}"); test++; Thread.Sleep(2000); socket.Dispose(); #endregion } } public static async void StartTestTcpSocket() { TcpListener tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1122); #region TcpListener socket //tcpListener.Server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1122)); //tcpListener.Server.Listen(10); #endregion tcpListener.Start(); int test = 1; Console.WriteLine($"TcpListener服务端 启动监听"); while (true) { #region TcpClient----AcceptTcpClientAsync //var tcpclient = await tcpListener.AcceptTcpClientAsync(); //var bytes = new byte[1024]; //var readdataCount = await tcpclient.GetStream().ReadAsync(bytes, 0, bytes.Length); //Console.WriteLine($"TcpListener服务端接收数据:{Encoding.UTF8.GetString(bytes, 0, readdataCount)}"); //bytes = Encoding.UTF8.GetBytes($"服务端已处理{test}"); //await tcpclient.GetStream().WriteAsync(bytes, 0, bytes.Length); //tcpclient.Dispose(); #endregion #region Socket----AcceptSocketAsync var socketConn = await tcpListener.AcceptSocketAsync(); //var socketConn = await socket.AcceptAsync(); var buffer = new byte[1024]; var socketConnReceCount = socketConn.Receive(buffer); Console.WriteLine($"TcpListener socket 服务端接收数据:{Encoding.UTF8.GetString(buffer, 0, socketConnReceCount)}"); Console.WriteLine($"TcpListener socket 服务端处理数据:{test}"); socketConn.Send(Encoding.UTF8.GetBytes($"服务端已处理{test}")); socketConn.Dispose(); #endregion } } #endregion
测试结果如下:
public class Program { static void Main(string[] args) { #region 测试TestTcpSocket TestTcpSocket(); #endregion Console.Read(); } }