Tcplistener服务端与tcpclient客户端使用--Socket监听服务端与Socketclient客户端使用

Tcplistener服务端与tcpclient客户端使用--Socket监听服务端与Socketclient客户端使用

  public static void Start()
        {
            //开启httplistener监听服务
            //Thread thread = new Thread(new ThreadStart(StartTcpListening))
            //{
            //    IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
            //};
            //thread.Start();

            //开启Socket监听服务
            Thread thread = new Thread(new ThreadStart(StartSocketListening))
            {
                IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
            };
            thread.Start();

            //测试
            //Thread threadClient = new Thread(new ThreadStart(TestTCPClient))
            //{
            //    IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
            //};
            //threadClient.Start();
        }

        /// <summary>
        /// 开启httplistener监听服务
        /// </summary>
        public static void StartTcpListening()
        {
            TcpListener tcpListener = null;
            #region TcpListener服务端
            try
            {
                while (true)
                {
                    try
                    {
                        tcpListener = new TcpListener(IPAddress.Any, 5566);
                        tcpListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                        tcpListener.Start();//tcpListener.Start(100);100是设置最大连接客户端数量
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);//监听服务启动失败,暂停1秒之后再启动监听服务
                    }
                    try
                    {
                        while (true)
                        {
                            //try
                            //{
                            //获取连接的客户端
                            TcpClient client = tcpListener.AcceptTcpClient();//Socket socket = tcpListener.AcceptSocket();
                            client.LingerState.Enabled = false;
                            string data = null;
                            byte[] bytes = new byte[1024];
                            NetworkStream stream = client.GetStream();
                            int i = stream.Read(bytes, 0, bytes.Length);
                            data = Encoding.Default.GetString(bytes, 0, i);
                            byte[] msg = Encoding.Default.GetBytes(data + "ok");
                            stream.Write(msg, 0, msg.Length);
                            stream.Flush();
                            #region 多个实时读取写入信息
                            //ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
                            //ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
                            //System.Diagnostics.Trace.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
                            Thread thread = new Thread(ProcessTcpData)
                            {
                                IsBackground = true
                            };
                            thread.Start(client);
                            #endregion

                            #region 只能单个实时读取写入信息
                            //NetworkStream stream = client.GetStream();
                            //int i;
                            //while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                            //{
                            //    data = Encoding.Default.GetString(bytes, 0, i);
                            //    System.Diagnostics.Trace.WriteLine("tcpListener Received: {0}", data);
                            //    //byte[] msg = Encoding.Default.GetBytes(data + "ok");
                            //    //stream.Write(msg, 0, msg.Length);
                            //    //System.Diagnostics.Trace.WriteLine("Sent: {0}", data);

                            //    byte[] msg = Encoding.Default.GetBytes(data + "-------ok");
                            //    stream.Write(msg, 0, msg.Length);
                            //    System.Diagnostics.Trace.WriteLine("tcpListener Sent: {0}", data);
                            //} 
                            #endregion

                            //client.Close();不需要关闭
                            //}
                            //catch (Exception e)
                            //{
                            //}
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            catch (Exception e)
            {
            }
            #endregion

            #region 监听本机的所有ip
            //Socket socketServer = null;
            //try
            //{
            //    socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //    socketServer.Bind(new IPEndPoint(IPAddress.Any, 7788));
            //    socketServer.Listen(10);
            //    //socketServer.LingerState.Enabled = false;

            //    while (true)
            //    {
            //        ////        var socket0 = socketServer.Accept();
            //        byte[] vs = new byte[1024];
            //        int count = socket0.Receive(vs);

            //        ////        byte[] vs1 = new byte[1024];
            //        socket0.Send(vs1);
            //    }
            //}
            //catch (Exception)
            //{
            //    throw;
            //}
            //finally
            //{
            //    socketServer.Close();
            //    //socketServer.Shutdown(SocketShutdown.Both);
            //}
            #endregion
        }

        /// <summary>
        /// tcplistener服务端接收到的数据处理
        /// </summary>
        /// <param name="clientData"></param>
        public static void ProcessTcpData(object clientData)
        {
            try
            {
                TcpClient client = clientData as TcpClient;
                NetworkStream stream = client.GetStream();
                string data = null;
                byte[] bytes = new byte[1024];
                int i;
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    data = Encoding.Default.GetString(bytes, 0, i);
                    System.Diagnostics.Trace.WriteLine("tcpListener Received: {0}", data);
                    //byte[] msg = Encoding.Default.GetBytes(data + "ok");
                    //stream.Write(msg, 0, msg.Length);
                    //System.Diagnostics.Trace.WriteLine("Sent: {0}", data);

                    byte[] msg = Encoding.Default.GetBytes(data + "-------ok");
                    stream.Write(msg, 0, msg.Length);
                    System.Diagnostics.Trace.WriteLine("tcpListener Sent: {0}", data);
                    ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
                    ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
                    System.Diagnostics.Trace.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
                }
            }
            catch (Exception e)
            {
            }
        }

        /// <summary>
        /// 测试TCPClient
        /// </summary>
        public static void TestTCPClient()
        {

            TcpClient tcpClient = null;
            try
            {
                //tcpClient = new TcpClient(new IPEndPoint(System.Net.Dns.Resolve(IPAddress.Any.ToString()).AddressList[0].Address, 7788));
                tcpClient = new TcpClient();
                tcpClient.Connect("127.0.0.1", 5566);
                if (tcpClient.Connected)
                {
                    String data = null;
                    int w = 0;
                    string senddata = null;
                    var stream = tcpClient.GetStream();
                    while (true)
                    {
                        //写入
                        senddata = $"哈哈哈kkkk2233--{++w}";
#if DEBUG
                        Console.WriteLine($"TcpClient Send: {senddata}");
#else
System.Diagnostics.Trace.WriteLine($"TcpClient Send: {senddata}");
#endif

                        byte[] sendBytes = Encoding.ASCII.GetBytes(senddata);
                        stream.Write(sendBytes, 0, sendBytes.Length);
                        //读出
                        byte[] receBytes = new byte[1024];
                        var rece = stream.Read(receBytes, 0, receBytes.Length);
                        data = Encoding.ASCII.GetString(receBytes, 0, rece);

#if DEBUG
                        Console.WriteLine($"TcpClient Received: {data}");
#else
System.Diagnostics.Trace.WriteLine($"TcpClient Received: {data}");
#endif
                        ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
                        ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
                        Console.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
                        Thread.Sleep(2000);
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(" TcpClient  Exception: {0}", e.InnerException.Message);
                //throw;
            }
            finally
            {
                tcpClient.Close();
            }
        }

        /// <summary>
        /// 开启Socket监听服务
        /// </summary>
        public static void StartSocketListening()
        {
            Socket socketServer = null;
            try
            {
                while (true)
                {
                    try
                    {
                        socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        socketServer.Bind(new IPEndPoint(IPAddress.Any, 7788));
                        socketServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                        //socketServer.LingerState.Enabled = false;
                        socketServer.Listen(100);//socketServer.Listen(100);100是设置最大连接客户端数量
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);//监听服务启动失败,暂停1秒之后再启动监听服务
                    }
                    try
                    {
                        while (true)
                        {
                            //获取连接的客户端
                            Socket socket = socketServer.Accept();
                            socket.LingerState.Enabled = false;
                            string data = null;
                            byte[] bytes = new byte[1024];
                            int i = socket.Receive(bytes);
                            data = Encoding.Default.GetString(bytes, 0, i);
                            byte[] arrSendMsg = Encoding.UTF8.GetBytes(data + "ok");
                            socket.Send(arrSendMsg);

                            #region 多个实时读取写入信息
                            //ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
                            //ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
                            //System.Diagnostics.Trace.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
                            Thread thread = new Thread(ProcessSocketData)
                            {
                                IsBackground = true
                            };
                            thread.Start(socket);
                            #endregion

                            #region 只能单个实时读取写入信息
                            //while (true)
                            //{
                            //    ////    var socket0 = socketServer.Accept();
                            //    byte[] vs = new byte[1024];
                            //    int count = socket0.Receive(vs);

                            //    ////    byte[] vs1 = new byte[1024];
                            //    socket0.Send(vs1);
                            //}
                            #endregion
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            catch (Exception e)
            {
            }
        }

        /// <summary>
        /// Socket服务端接收到的数据处理
        /// </summary>
        /// <param name="clientData"></param>
        public static void ProcessSocketData(object clientData)
        {
            try
            {
                Socket socketServer = clientData as Socket;
                while (true)
                {
                    try
                    {
                        byte[] serverRecMsg = new byte[1024];
                        int length = socketServer.Receive(serverRecMsg);
                        string strSRecMsg = Encoding.UTF8.GetString(serverRecMsg, 0, length);
                        socketServer.Send(Encoding.UTF8.GetBytes(strSRecMsg + "ok"));
                        //System.Diagnostics.Trace.WriteLine($"Socket Sent: {strSRecMsg}");
                        //ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
                        //ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
                        //System.Diagnostics.Trace.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
                        serverRecMsg.DefaultIfEmpty();
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            catch (Exception e)
            {
            }
        }

        /// <summary>
        /// 测试Socketlient
        /// </summary>
        public static void TestSocketlient()
        {

            Socket socketClient = null;
            try
            {
                //tcpClient = new TcpClient(new IPEndPoint(System.Net.Dns.Resolve(IPAddress.Any.ToString()).AddressList[0].Address, 7788));
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //socketClient.Connect(new IPEndPoint(IPAddress.Any, 7788));
                socketClient.Connect("127.0.0.1", 7788);

                if (socketClient.Connected)
                {
                    String data = null;
                    int w = 0;
                    string senddata = null;
                    while (true)
                    {
                        //写入
                        senddata = $"哈哈哈kkkk2233--{++w}";
#if DEBUG
                        Console.WriteLine($"SocketClient Send: {senddata}");
#else
System.Diagnostics.Trace.WriteLine($"SocketClient Send: {senddata}");
#endif

                        byte[] sendBytes = Encoding.ASCII.GetBytes(senddata);
                        socketClient.Send(sendBytes);
                        //读出
                        byte[] receBytes = new byte[1024];
                        var rece = socketClient.Receive(receBytes);
                        data = Encoding.ASCII.GetString(receBytes, 0, rece);

#if DEBUG
                        Console.WriteLine($"SocketClient Received: {data}");
#else
System.Diagnostics.Trace.WriteLine($"SocketClient Received: {data}");
#endif
                        ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
                        ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
                        Console.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
                        Thread.Sleep(2000);
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(" TcpClient  Exception: {0}", e.InnerException.Message);
                //throw;
            }
            finally
            {
                socketClient.Shutdown(SocketShutdown.Both);
                socketClient.Disconnect(true);
                socketClient.Close();
            }
        }

 

posted @ 2021-09-28 15:31  龙骑科技  阅读(237)  评论(0编辑  收藏  举报