C#—简单的tcp服务端

C#—简单的tcp服务端

猿掌柜
2021-11-23 / 0 评论 / 43 阅读 / 正在检测是否收录...

简单的tcp服务端

代码如下

private static TcpListener tcpListener;
        private static Thread listenThread;
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome!");
            Console.WriteLine(DateTime.Now);
            tcpListener = new TcpListener(IPAddress.Any, 8888);
            listenThread = new Thread(new ThreadStart(ListenForClients));
            listenThread.Start();
            try
            {
                

            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.ToString());
            }
        }
private static void ListenForClients()
        {
            tcpListener.Start();

            while (true)
            {
                TcpClient client = tcpListener.AcceptTcpClient();
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }
private static void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            Console.WriteLine("客户端 @[{0}] 已连接 @{1}", tcpClient.Client.RemoteEndPoint, DateTime.Now.ToString());

            NetworkStream clientStream = tcpClient.GetStream();
      byte[] cmdmsg = new byte[1024];
            while (true)
            {
               try
                {
                    bytesRead = clientStream.Read(cmdmsg, 0, cmdmsg.Length);
                }
                catch
                {
                    Console.WriteLine("Error:receive msg error");
                    break;
                }
                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    Console.WriteLine("客户端 @[{0}] 离线 @{1}", tcpClient.Client.RemoteEndPoint, DateTime.Now.ToString());
                    break;
                }
           }
}
0

评论 (0)

取消