zoukankan      html  css  js  c++  java
  • 测试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();
            }
        }

  • 相关阅读:
    Tomcat修改端口号
    如何修改localhost为自己指定的域名
    Tomcat启动时启动窗口中文乱码问题的解决方案
    Java Web 项目jsp页面无法加载样式
    vue 父传子(通过属性传递)
    vue 父传子 讲解
    表白小爱心
    响应式开发
    组件的重复调用
    reduce
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/14150251.html
Copyright © 2011-2022 走看看