C#套接字编程

标签 c# sockets

<分区>

嘿,我正在为 C# 异步套接字编程做噩梦。你能给我指一个指南或教程或一本深入解释异步编程的书吗?如果可能包含如何在 Begin Send/Receive 函数中使用 state 参数来处理多个客户端。

最佳答案

服务器可以按这样的场景组织:用于客户端连接的独立线程监听端口。

 
 /// Async server
 public class AsyncServer
 {
     /// Server socket
     private Socket _serverSocket;

     /// Element for sync wait 
     private static ManualResetEvent _connectionMutex =
              new ManualResetEvent(false);

     /// Client handler
     private ClientManager _clientManager;

     public AsyncServer(string ipAddrees, int port)
     {
         try
         {             
             this._serverSocket = new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream, ProtocolType.Tcp);

             this._serverSocket.Bind(
               new IPEndPoint(IPAddress.Parse(ipAddrees), port));

         }
         catch (Exception ex)
         {
             throw new Exception("Server Init Error.", ex);
         }
     }

     private BackgroundWorker _listenThread = new BackgroundWorker();

     public void Start()
     {
         this._clientManager = new ClientManager(this._clientConnections);

         this._listenThread.WorkerReportsProgress = true;
         this._listenThread.WorkerSupportsCancellation = true;
         this._listenThread.DoWork +=
              new DoWorkEventHandler(ListenThread_DoWork);

         this._listenThread.RunWorkerAsync(this._serverSocket);
     }

     /// Thread for listening port
     private void ListenThread_DoWork(object sender, DoWorkEventArgs e)
     {
         Socket serverSocket = (Socket)e.Argument;

         serverSocket.Listen(100);

         while (true)
         {
             // reset mutex
             _connectionMutex.Reset();

             serverSocket.BeginAccept(
             new AsyncCallback(this.AcceptCallback), this._serverSocket);

             // waiting for the next connection
             _connectionMutex.WaitOne();
         }
     }

     /// List of client connections
     private List _clientConnections = new List();  

     public int ConnectionsCount
     {
         get { return this._clientConnections.Count; }
     }

     /// Callback method for handling connections
     private void AcceptCallback(IAsyncResult asyncResult)
     {
         _connectionMutex.Set();

         Socket serverSocket = (Socket)asyncResult.AsyncState;
         Socket clientSocket = (Socket)serverSocket.EndAccept(asyncResult);
         this._clientConnections.Add(clientSocket);

         this._clientManager.HandleClient(clientSocket);
     }

 }
 

AcceptCallback(IAsyncResult asyncResult) 方法处理所有新的客户端连接并将传输到 ClientManager,后者为每个客户端创建单独的线程。

 

   public class ClientManager
   {       

       private List _clientProcessors = new List();


       private List _connections;       

       public ClientManager(List connections)
       {
           this._connections = connections;
       }

       /// Handling of client connection      
       public void HandleClient(Socket clientSocket)
       {
           BackgroundWorker clientProcessor = new BackgroundWorker();
           clientProcessor.DoWork += new DoWorkEventHandler(ClientProcessing);

           this._clientProcessors.Add(clientProcessor);

           List args = new List();
           // 
           // args.Add(...);           

           clientProcessor.RunWorkerAsync(args);
       }      

       private void ClientProcessing(object sender, DoWorkEventArgs e)
       {
           // reading args
           List args = (List)e.Argument;          

           ProtocolSerializer serializer = new ProtocolSerializer();

           try
           {
               while (socket.Connected)
               {               
                   // ...

               }
           }
           catch (SocketException)
           {
              // ...
           }
           catch (Exception)
           {
              // ...
           }
       }
   }

关于C#套接字编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1392514/

相关文章:

javascript - IdentityServer4 oidc 如何知道从配置重定向到哪里

c# - System.Net.Sockets.Socket() 如何使用它的参数?

sockets - 是否可以将套接字内存映射到虚拟内存?

c++ - Linux socket C/C++-检查ip/port是否已在使用的最佳方法是什么?

c# - 具有其他依赖项的 ConfigurationProvider

c# - Mysql 到 Linq 查询

使用嵌入式 FPGA 中的 MAC 地址与套接字进行通信

java - 通过 Singleton 的 Socket 服务器,使用属性文件中的参数

c# - 我的 System.Management.* 类在哪里?

c# - 不同 DbContext 和不同模式之间的 Entity Framework 关系