Модераторы: gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Для чего создается два сокета? 
V
    Опции темы
Barabeo
Дата 3.6.2011, 12:24 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 234
Регистрация: 2.10.2010

Репутация: нет
Всего: нет



В проге создается два сокета прослушивающий и рабочий - для чего?

Код

const int MAX_CLIENTS = 10;
        
        public AsyncCallback    pfnWorkerCallBack ;
        private  Socket            m_mainSocket;
        private  Socket []        m_workerSocket = new Socket[10];
        private int                    m_clientCount = 0;
        private StreamWriter tt;
        
        public SocketServer()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            tt = new StreamWriter("out.txt", true);
            // Display the local IP address on the GUI
            textBoxIP.Text = GetIP();
        }
        
        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new SocketServer());
        }
        
        
        void ButtonStartListenClick(object sender, System.EventArgs e)
        {
            try
            {
                // Check the port value
                if(textBoxPort.Text == ""){
                    MessageBox.Show("Please enter a Port Number");
                    return;
                }
                string portStr = textBoxPort.Text;
                int port = System.Convert.ToInt32(portStr);
                // Create the listening socket...
                m_mainSocket = new Socket(AddressFamily.InterNetwork, 
                                          SocketType.Stream, 
                                          ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint (IPAddress.Any, port);
                // Bind to local IP Address...
                m_mainSocket.Bind( ipLocal );
                // Start listening...
                m_mainSocket.Listen (4);
                // Create the call back for any client connections...
                m_mainSocket.BeginAccept(new AsyncCallback (OnClientConnect), null);
                
                UpdateControls(true);
                
            }
            catch(SocketException se)
            {
                MessageBox.Show ( se.Message );
            }

        }
        private void UpdateControls( bool listening ) 
        {
            buttonStartListen.Enabled    = !listening;
            buttonStopListen.Enabled    = listening;
        }    
        // This is the call back function, which will be invoked when a client is connected
        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                m_workerSocket[m_clientCount] = m_mainSocket.EndAccept (asyn);
                // Let the worker Socket do the further processing for the 
                // just connected client
                WaitForData(m_workerSocket[m_clientCount]);
                // Now increment the client count
                ++m_clientCount;
                // Display this client connection as a status message on the GUI    
                String str = String.Format("Client # {0} connected", m_clientCount);
                //textBoxMsg.Text = str;
                                
                // Since the main Socket is now free, it can go back and wait for
                // other clients who are attempting to connect
                m_mainSocket.BeginAccept(new AsyncCallback ( OnClientConnect ),null);
            }
            catch(ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection: Socket has been closed\n");
            }
            catch(SocketException se)
            {
                MessageBox.Show ( se.Message );
            }
            
        }
        public class SocketPacket
        {
            public System.Net.Sockets.Socket m_currentSocket;
            public byte[] dataBuffer = new byte[4096];
        }
        
        // Start waiting for data from the client
        public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if  ( pfnWorkerCallBack == null )
                {        
                    // Specify the call back function which is to be 
                    // invoked when there is any write activity by the 
                    // connected client
                    pfnWorkerCallBack = new AsyncCallback (OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket ();
                theSocPkt.m_currentSocket    = soc;
                // Start receiving any data written by the connected client
                // asynchronously
                soc .BeginReceive 
                (    
                    theSocPkt.dataBuffer, 
                    0, 
                    theSocPkt.dataBuffer.Length,
                    SocketFlags.None,
                    pfnWorkerCallBack,
                    theSocPkt
                );
            }

            catch(SocketException se)
            {
                MessageBox.Show (se.Message );
            }

        }
       
        // This the call back function which will be invoked when the socket
        // detects any client writing of data on the stream
        public  void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState ;

                int iRx  = 0 ;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream 
                // by the client
                iRx = socketData.m_currentSocket.EndReceive (asyn);
                char[] chars = new char[iRx];
                System.Text.Decoder d = System.Text.Encoding.ASCII.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer, 
                                         0, iRx, chars, 0);
                System.String szData = new System.String(chars);
                richTextBoxReceivedMsg.AppendText(szData);
                
                tt.Write(szData);
                // Continue the waiting for data on the Socket
                WaitForData( socketData.m_currentSocket );
            }
            catch (ObjectDisposedException )
            {
                System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
            }
            catch(SocketException se)
            {
                MessageBox.Show (se.Message );
            }
        }
        
        
        void ButtonStopListenClick(object sender, System.EventArgs e)
        {
            CloseSockets();            
            UpdateControls(false);
        }
    
       String GetIP()
       {       
            String strHostName = Dns.GetHostName();
        
            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
        
            // Grab the first IP addresses
            String IPStr = "";
            foreach(IPAddress ipaddress in iphostentry.AddressList){
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
       }
       void ButtonCloseClick(object sender, System.EventArgs e)
       {
           tt.Close();
            CloseSockets();
            Close();
       }
       void CloseSockets()
       {
            if(m_mainSocket != null && m_mainSocket.Connected){
                m_mainSocket.Close();
            }
            for(int i = 0; i < m_clientCount; i++){
                if(m_workerSocket[i] != null){
                    if(m_workerSocket[i].Connected){
                        m_workerSocket[i].Close();
                    }
                    m_workerSocket[i] = null;
                }
            }    
       }
    }
}


PM MAIL   Вверх
jonie
Дата 3.6.2011, 15:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 5613
Регистрация: 21.8.2005
Где: Владимир

Репутация: 15
Всего: 118



комментарии читать уже не в моде?
Код

                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                m_workerSocket[m_clientCount] = m_mainSocket.EndAccept (asyn);
                // Let the worker Socket do the further processing for the 
                // just connected client
                WaitForData(m_workerSocket[m_clientCount]);
                // Now increment the client count
                ++m_clientCount;
                // Display this client connection as a status message on the GUI    
                String str = String.Format("Client # {0} connected", m_clientCount);
                //textBoxMsg.Text = str;
                                

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                // Since the main Socket is now free, it can go back and wait for
                // other clients who are attempting to connect
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                m_mainSocket.BeginAccept(new AsyncCallback ( OnClientConnect ),null);



--------------------
Что-то не поняли? -> Напейтесь до зеленых человечков... эта сверхцивилизация Вам поможет...
PM MAIL Jabber   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
cully
mr.DUDA
Exception

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, cully, mr.DUDA, Exception.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Распределённые приложения и сеть | Следующая тема »


 




[ Время генерации скрипта: 0.0483 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.