• 测试Socket监听请求----处理Socket


    测试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();
            }
        }

  • 相关阅读:
    Session 0 隔离
    在DIV容器中使用浮动元素
    Linq学习总结(5)——标准查询运算符
    Linq学习总结(3)——yield
    消息拦截的简单实现
    网站内容可访问性——关于背景与前景颜色的对比标准
    CSS优先级
    Linq学习总结(4)——Lambda表达式
    element ui表格的校验和自定义校验规则
    vue 递归组件的两种方法
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/14150251.html
Copyright © 2020-2023  润新知