⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadechoserver.cs

📁 在Echo服务器上的多线程问题
💻 CS
字号:
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;

class ThreadEchoServer
{
   public static void Main()
   {
      //产生TcpListener对象,侦听通信端口7
      TcpListener myListener = new TcpListener(7);
      try
      {
          //让TcpListener对象开始侦听用户端的连接
          myListener.Start();
      }
      catch(SocketException se)
      {
          //若无法成功侦听,则显示出错误信息,并退出程序
          Console.WriteLine("Could not listen to specified interface!!");
          return;
      }
      //显示Echo服务器成功启动的信息
      Console.WriteLine("Echo Server has been created successfully!!");
      Console.WriteLine("Waiting for client connection..............");

      while(true)
      {
         //当侦听到有用户端连接时,调用Accept以完成连接
         Socket theConnection = myListener.AcceptSocket();
         //显示用户端Socket的相关信息
         PrintClientInfo((IPEndPoint)theConnection.RemoteEndPoint);
 
         //产生一个ThreadProcessor对象
         ThreadProcessor tp = new ThreadProcessor(theConnection);
         //创建一个线程,执行ThreadProcessor对象中的ProcessService
         Thread SocketThread = new Thread(new ThreadStart(tp.ProcessService));
         //启动所产生的线程,开始服务用户端应用程序
         SocketThread.Start();
      }
   }
 
   //显示用户端Socket信息的method  
   public static void PrintClientInfo(IPEndPoint clientEP)
   {
      //获取用户端Socket的IP地址
      IPAddress clientIP = clientEP.Address;
      Console.WriteLine("We have a client connected from IP:" +clientIP.ToString());  
   }
}


class ThreadProcessor
{
   private Socket client;

   public ThreadProcessor(Socket clientSocket)
   {
      client = clientSocket;
   }

   public void ProcessService()
   {
      int bytes = 0;
      Byte[] RecvBytes = new Byte[256];

      while(true)
      {
         try
         {
            //读取用户端所送出来的数据
            bytes = client.Receive(RecvBytes,RecvBytes.Length,0);
         }
         catch(SocketException se)
         {
            Console.WriteLine("An error occurs while reading data!!");
            break;
         }
         //若读取失败则退出循环
         if (bytes == 0)  break;

         try
         {
            //将所读取到的数据RecvBytes原封不动的送回
            client.Send(RecvBytes,bytes,0);
         }
         catch(SocketException se)
         {
             Console.WriteLine("An error occurs while sending data!!");
             break;
         }
      }
      //关闭与用户端的连接
      client.Close();
      Console.WriteLine("Client is disconnect......");
   }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -