2013-02-20 57 views
11

मैं अभी सी # में सॉकेट प्रोग्रामिंग शुरू कर रहा हूं और अब इस समस्या से थोड़ा फंस गया हूं। प्रत्येक क्लाइंट के लिए थ्रेड बनाने के बिना आप एक ही सर्वर पर एकाधिक क्लाइंट को कैसे प्रबंधित करते हैं?सॉकेट प्रोग्रामिंग एकाधिक क्लाइंट एक सर्वर

10 क्लाइंट कहने पर प्रत्येक क्लाइंट के लिए एक थ्रेड ठीक काम करता है लेकिन यदि ग्राहक संख्या 1000 क्लाइंट तक जाती है तो उनमें से प्रत्येक के लिए एक थ्रेड तैयार कर रहा है? अगर ऐसा करने के लिए कोई और तरीका है तो कृपया मुझे टेलिफोन कर सकते हैं?

+1

http://www.codeproject.com/Articles/83102/C-SocketAsyncEventArgs-High-Performance-Socket-Cod ... यदि आप 'async सॉकेट सी #' के लिए खोज करते हैं तो वहां लगभग दस लाख लेख हैं। – atlaste

+0

यदि आप "सॉकेट प्रोग्रामिंग सी # परिचय" पर Google के सैकड़ों उदाहरण हैं। यदि आप इसे पसंद करते हैं तो विषय पर बहुत अच्छे यू ट्यूब ट्यूब भी लोड करते हैं। – MarcF

उत्तर

19

एसिंक्रोनस सर्वर का उपयोग करने का प्रयास करें। निम्न उदाहरण प्रोग्राम एक सर्वर बनाता है जो ग्राहकों से कनेक्शन अनुरोध प्राप्त करता है। सर्वर को एसिंक्रोनस सॉकेट के साथ बनाया गया है, इसलिए क्लाइंट से कनेक्शन की प्रतीक्षा करते समय सर्वर एप्लिकेशन का निष्पादन निलंबित नहीं किया जाता है। एप्लिकेशन क्लाइंट से एक स्ट्रिंग प्राप्त करता है, कंसोल पर स्ट्रिंग प्रदर्शित करता है, और उसके बाद स्ट्रिंग को क्लाइंट पर वापस ले जाता है। क्लाइंट से स्ट्रिंग में संदेश के अंत को सिग्नल करने के लिए स्ट्रिंग "" होनी चाहिए।

using System; 
    using System.Net; 
    using System.Net.Sockets; 
    using System.Text; 
    using System.Threading; 

    // State object for reading client data asynchronously 
    public class StateObject { 
     // Client socket. 
     public Socket workSocket = null; 
     // Size of receive buffer. 
     public const int BufferSize = 1024; 
     // Receive buffer. 
     public byte[] buffer = new byte[BufferSize]; 
    // Received data string. 
     public StringBuilder sb = new StringBuilder(); 
    } 

    public class AsynchronousSocketListener { 
     // Thread signal. 
     public static ManualResetEvent allDone = new ManualResetEvent(false); 

     public AsynchronousSocketListener() { 
     } 

     public static void StartListening() { 
      // Data buffer for incoming data. 
      byte[] bytes = new Byte[1024]; 

      // Establish the local endpoint for the socket. 
      // The DNS name of the computer 
      // running the listener is "host.contoso.com". 
      IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
      IPAddress ipAddress = ipHostInfo.AddressList[0]; 
      IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 

      // Create a TCP/IP socket. 
      Socket listener = new Socket(AddressFamily.InterNetwork, 
       SocketType.Stream, ProtocolType.Tcp); 

      // Bind the socket to the local endpoint and listen for incoming connections. 
      try { 
       listener.Bind(localEndPoint); 
       listener.Listen(100); 

       while (true) { 
        // Set the event to nonsignaled state. 
        allDone.Reset(); 

        // Start an asynchronous socket to listen for connections. 
        Console.WriteLine("Waiting for a connection..."); 
        listener.BeginAccept( 
         new AsyncCallback(AcceptCallback), 
         listener); 

        // Wait until a connection is made before continuing. 
        allDone.WaitOne(); 
       } 

      } catch (Exception e) { 
       Console.WriteLine(e.ToString()); 
      } 

      Console.WriteLine("\nPress ENTER to continue..."); 
      Console.Read(); 

     } 

     public static void AcceptCallback(IAsyncResult ar) { 
      // Signal the main thread to continue. 
      allDone.Set(); 

      // Get the socket that handles the client request. 
      Socket listener = (Socket) ar.AsyncState; 
      Socket handler = listener.EndAccept(ar); 

      // Create the state object. 
      StateObject state = new StateObject(); 
      state.workSocket = handler; 
      handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
       new AsyncCallback(ReadCallback), state); 
     } 

     public static void ReadCallback(IAsyncResult ar) { 
      String content = String.Empty; 

      // Retrieve the state object and the handler socket 
      // from the asynchronous state object. 
      StateObject state = (StateObject) ar.AsyncState; 
      Socket handler = state.workSocket; 

      // Read data from the client socket. 
      int bytesRead = handler.EndReceive(ar); 

      if (bytesRead > 0) { 
       // There might be more data, so store the data received so far. 
       state.sb.Append(Encoding.ASCII.GetString(
        state.buffer,0,bytesRead)); 

       // Check for end-of-file tag. If it is not there, read 
       // more data. 
       content = state.sb.ToString(); 
       if (content.IndexOf("<EOF>") > -1) { 
        // All the data has been read from the 
        // client. Display it on the console. 
        Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", 
         content.Length, content); 
        // Echo the data back to the client. 
        Send(handler, content); 
       } else { 
        // Not all data received. Get more. 
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
        new AsyncCallback(ReadCallback), state); 
       } 
      } 
     } 

     private static void Send(Socket handler, String data) { 
      // Convert the string data to byte data using ASCII encoding. 


     byte[] byteData = Encoding.ASCII.GetBytes(data); 

     // Begin sending the data to the remote device. 
     handler.BeginSend(byteData, 0, byteData.Length, 0, 
      new AsyncCallback(SendCallback), handler); 
    } 

    private static void SendCallback(IAsyncResult ar) { 
     try { 
      // Retrieve the socket from the state object. 
      Socket handler = (Socket) ar.AsyncState; 

      // Complete sending the data to the remote device. 
      int bytesSent = handler.EndSend(ar); 
      Console.WriteLine("Sent {0} bytes to client.", bytesSent); 

      handler.Shutdown(SocketShutdown.Both); 
      handler.Close(); 

     } catch (Exception e) { 
      Console.WriteLine(e.ToString()); 
     } 
    } 

    public static int Main(String[] args) { 
     StartListening(); 
     return 0; 
    } 
} 

यह सबसे अच्छा समाधान होगा।

+0

मैं इस प्रश्न का उपयोग इस प्रश्न में कर रहा हूं, लेकिन किसी कारण से कॉलबैक तुरंत नहीं होता है लेकिन केवल 20 सेकंड बाद ही होता है। क्या आप इसे देख सकते हैं? http://stackoverflow.com/questions/18418613/socket-buffers-the-data-it-receives –

+0

यह समाधान अपूर्ण है क्योंकि यह मानता है कि आपके पास केवल एक नेटवर्क एडाप्टर है। यदि आपके पास दो या दो से अधिक नेटवर्क एडेप्टर हैं और आप उन सभी को सुनना चाहते हैं तो यह समाधान विफल हो जाता है। –

+0

ऑलडोन कॉलबैक में दिखाई नहीं दे रहा है। क्योंकि आपका कॉलबैक एक स्थिर संशोधक का उपयोग करता है। –

1

थ्रेड ठीक काम कर सकते हैं लेकिन शायद ही कभी कई ग्राहकों को अच्छी तरह से स्केल कर सकते हैं। इसे संभालने के दो आसान तरीके और कई जटिल तरीके हैं, यहां कुछ छद्म कोड है कि आमतौर पर आपको एक सिंहावलोकन देने के लिए आसान दो कैसे बनाए जाते हैं।

चयन()

यह जाँच करने के लिए जो सॉकेट नए ग्राहकों या उन पर इंतजार कर डेटा है एक फोन है, एक ठेठ कार्यक्रम कुछ इस तरह लग रहा है।

server = socket(), bind(), listen() 
while(run) 
    status = select(server) 
    if has new client 
     newclient = server.accept() 
     handle add client 
    if has new data 
     read and handle data 

जिसका मतलब है कोई सूत्र कई ग्राहकों को संभालने के लिए की जरूरत है, लेकिन यह वास्तव में अच्छी तरह से स्केल नहीं करता है या तो अगर संभाल डेटा एक लंबे समय ले, तो आप नए डेटा नहीं पढ़ा होगा या स्वीकार नए ग्राहकों तक यह काम होने पर ।

Async सॉकेट

इस सॉकेट जो तरह का चयन ऊपर निकाला जाता है से निपटने का एक और तरीका है। आपने बस सामान्य घटनाओं के लिए कॉलबैक स्थापित किए हैं और फ्रेमवर्क को इतनी भारी उठाने नहीं देते हैं।

function handleNewClient() { do stuff and then beginReceive(handleNewData) } 
function handleNewData() { do stuff and then beginReceive(handleNewData) } 
server = create, bind, listen etc 
server.beginAddNewClientHandler(handleNewClient) 
server.start() 

मुझे लगता है कि यदि आपके डेटा हैंडलिंग में काफी समय लगता है तो यह बेहतर होना चाहिए। आप किस प्रकार का डेटा हैंडलिंग करेंगे?

0

This एक अच्छा प्रारंभिक बिंदु हो सकता है। यदि आप 1 थ्रेड < -> 1 क्लाइंट से बचना चाहते हैं; तो आपको .NET में प्रदान की गई एसिंक सॉकेट सुविधाओं का उपयोग करना चाहिए। यहां उपयोग करने के लिए कोर ऑब्जेक्ट SocketAsyncEventArgs है।

संबंधित मुद्दे