C# Socket 通讯测试类

    初学者都会选择网络通讯作为学习课题。但 Socket 编程确实有不少难度,因为太过抽象,连测试都不知道从何做起。结果是由于理解上的误差,导致编程失败。不得已,就从网上找些同样是半生不熟的示例代码来凑合,但还是因为不明觉里,不敢修改。给日后的应用代码无尽的困扰

    这里介绍一款 多用户网络通讯测试类。之所以称为 测试类,是因为他离实用还相距甚远。只包含了最基础的操作。

    

    /// <summary>
    /// 交流
    /// Socket TCP 网络通讯测试
    /// </summary>
    public class Interflow
    {
        private Socket server;
        //listener //
        public void Server(string ip = "0.0.0.0", int port = 1000)
        {
            ThreadPool.QueueUserWorkItem(h => select(ip,port));
        }

        /// <summary>
        /// 使用 Socket.Select 的服务端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        void select(string ip, int port)
        {
            var local = IPAddress.Parse(ip);
            var iep = new IPEndPoint(local, port);
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 将套接字与本地终结点绑定    
            server.Bind(iep);

            //在本地13000端口号上进行监听    
            server.Listen(20);

            Console.WriteLine("等待客户机进行连接......");
            List<Socket> socketList = new List<Socket>();
            socketList.Add(server);

            while (true)
            {
                List<Socket> temp = socketList.ToList();
                Socket.Select(temp, null, null, 1000); //监视套接字的变化
                int count = temp.Count;
                for (int i = 0; i < count; i++)
                {
                    if (temp[i].Equals(server)) //如果是主套接字,则创建并保存客户套接字
                    {
                        Socket client = socketList[i].Accept();
                        socketList.Add(client);
                    }
                    else //否则对该客户套接字完成一轮会话,这里仅将收到的数据再发送回去
                    {
                        byte[] bytes = new byte[1024];
                        int len;
                        if ((len = temp[i].Receive(bytes)) > 0)
                        {
                            var text = System.Text.Encoding.Default.GetString(bytes, 0, len);
                            //Console.WriteLine("收到数据:" + text);
                            temp[i].Send(Encoding.Default.GetBytes("收到数据:" + text));
                        }
                        else
                        {
                            temp[i].Close();
                            socketList.Remove(temp[i]);
                            Console.WriteLine("关闭");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 测试用客户端
        /// </summary>
        /// <param name="input"></param>
        public static void ClientTest(string input)
        {
            Socket client;
            byte[] buf = new byte[1024];
            IPAddress local = IPAddress.Parse("127.0.0.1");
            IPEndPoint iep = new IPEndPoint(local, 1000);
            try
            {
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(iep);
            }                
            catch (SocketException)
            {
                Console.WriteLine("无法连接到服务器!");
                return;
            }

            //模拟 3 次交互
            var tid = Thread.CurrentThread.ManagedThreadId;
            for (var i = 0; i < 3; i++)
            {
                input = string.Format("[{0}]第 {1} 次: {2}", tid,i+1, input);
                client.Send(Encoding.Default.GetBytes(input));
                var len = 0;
                var bytes = new byte[128];
                if ((len = client.Receive(bytes)) > 0)
                {
                    var text = System.Text.Encoding.Default.GetString(bytes, 0, len);
                    Console.WriteLine("返回数据:" + text);
                }
                Thread.Sleep(50);
            }
            Console.WriteLine("[{0}] 断开与服务器的连接......", tid);
            client.Close();
        }

        /// <summary>
        /// 测试
        /// </summary>
        public static void Test()
        {
            var s = new Interflow();
            s.Server();
            Thread.Sleep(1000);
            //在子线程里创建客户端,用以模拟多用户场合
            new Thread(new ThreadStart(() => Interflow.ClientTest("abcd"))).Start();
            new Thread(new ThreadStart(() => Interflow.ClientTest("123"))).Start();
            new Thread(new ThreadStart(() => Interflow.ClientTest("ABC"))).Start();
            new Thread(new ThreadStart(() => Interflow.ClientTest("测试"))).Start();
        }
    }

使用方式:

Interflow.Test();


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页