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