Esempio n. 1
0
 /// <summary>
 /// The routine that is executed by the listening thread.
 /// </summary>
 private void ReceiveMsg()
 {
     try
     {
         // Buffer messages
         byte[]        data   = new byte[1024];
         MessageBuffer buffer = new MessageBuffer((string message) =>
         {
             if (message.Equals(CommunicationConstants.COMM_DISCONNECT_MSG))
             {
                 IsConnected = false;
             }
             else
             {
                 _receiveMessageCallback(message);
             }
         });
         // Keep listening for messages
         while (IsConnected)
         {
             // Receive message
             int    recv       = _socket.Receive(data);
             string stringdata = Encoding.UTF8.GetString(data, 0, recv);
             // Pass message to buffer
             buffer.SubmitFragment(stringdata);
             // counts empty StringData to avoid deadlock
             if (stringdata.Equals(""))
             {
                 _nullMessageCounter++;
             }
             else
             {
                 _nullMessageCounter = 0;
                 // Log message
                 _logger("<<<<::" + stringdata);
             }
             if (_nullMessageCounter > 10)
             {
                 Disconnect();
             }
         }
     }
     catch (Exception ex)
     {
         // Disconnect when running into problems
         _logger("Terminating connection due to an error:" + Environment.NewLine + ex.Message);
         Disconnect();
     }
 }
Esempio n. 2
0
        /// <summary>
        /// Called for every new connection request.
        /// </summary>
        /// <param name="ar">The async result containing the server socket</param>
        public void OnConnectRequest(IAsyncResult ar)
        {
            //Init SOCKET
            Socket serverSocket    = (Socket)ar.AsyncState;
            Socket newClientSocket = serverSocket.EndAccept(ar);
            string welcomeMessage  = "Welcome! The Server is Connected!";

            byte[] byteDateLine = System.Text.Encoding.UTF8.GetBytes(welcomeMessage);
            //show message to client and show the connection infos
            string ip = newClientSocket.RemoteEndPoint.ToString();

            _logger(ip + "::connection established:" + DateTime.Now.ToString("G"));
            newClientSocket.Send(byteDateLine, byteDateLine.Length, 0);
            // Buffer messages from the client
            bool          terminated = false;
            MessageBuffer buffer     = new MessageBuffer((string message) => { HandleMetaMessage(newClientSocket, message, out terminated); });

            // Wait for another new client connection
            serverSocket.BeginAccept(new AsyncCallback(OnConnectRequest), serverSocket);
            // Start receiving messages until communication termination
            try
            {
                while (!terminated)
                {
                    // Read the message
                    int    recv       = newClientSocket.Receive(byteDateLine);
                    string stringdata = Encoding.UTF8.GetString(byteDateLine, 0, recv);
                    // Pass message to buffer
                    buffer.SubmitFragment(stringdata);
                }
            }
            catch (SocketException ex)
            {
                try
                {
                    // Log exception
                    _logger(newClientSocket.RemoteEndPoint.ToString() + "::exception:" + ex.Message + ":" + DateTime.Now.ToString("G"));
                    // Try to remove the client
                    bool foundClient = false; ClientType clientType = ClientType.R; int clientID = 0;
                    if (_botClients.Values.Contains(newClientSocket))
                    {
                        foundClient = true; clientType = ClientType.R; clientID = _botClients.First(kvp => kvp.Value == newClientSocket).Key;
                    }
                    if (_controlClients.Values.Contains(newClientSocket))
                    {
                        foundClient = true; clientType = ClientType.C; clientID = _controlClients.First(kvp => kvp.Value == newClientSocket).Key;
                    }
                    if (_iStationClients.Values.Contains(newClientSocket))
                    {
                        foundClient = true; clientType = ClientType.I; clientID = _iStationClients.First(kvp => kvp.Value == newClientSocket).Key;
                    }
                    if (_oStationClients.Values.Contains(newClientSocket))
                    {
                        foundClient = true; clientType = ClientType.O; clientID = _oStationClients.First(kvp => kvp.Value == newClientSocket).Key;
                    }
                    if (foundClient)
                    {
                        RemoveDeadClient(clientType, clientID, newClientSocket);
                    }
                }
                catch (ObjectDisposedException) { _logger(ip + "::exception:" + ex.Message + ":" + DateTime.Now.ToString("G")); }
            }
        }