Пример #1
0
        /// <summary>
        /// Send data.
        /// </summary>
        /// <param name="pConnectioHandle">Network connection to use</param>
        /// <param name="pMsg">Data to send</param>
        /// <returns>Send status</returns>
        public bool Send(TcpConnectionHandle pConnectioHandle, byte[] pMsg)
        {
            try
            {
                if (pConnectioHandle != null)
                {
                    TcpClient tcpClient = pConnectioHandle.ConnectionClient;
                    if (tcpClient != null & tcpClient.Connected)
                    {
                        NetworkStream clientStream = tcpClient.GetStream();

                        if (clientStream != null)
                        {
                            clientStream.Write(pMsg, 0, pMsg.Length);
                            clientStream.Flush();
                            return(true);
                        }
                        return(false);
                    }
                    return(false);
                }
                return(false);
            }
            catch (Exception ex)
            {
                Logger.Error("Exception raised sending message.", ex);
                return(false);
            }
        }
Пример #2
0
 /// <summary>
 /// Create a new MessageData object.
 /// </summary>
 /// <param name="pMsg">Message content</param>
 /// <param name="pMsgLength">Message length</param>
 /// <param name="pRemoteEndPoint">Remote endpoint</param>
 /// <param name="pCnxHandle">Handle of the TCP connection</param>
 public MessageData(byte[] pMsg, int pMsgLength, EndPoint pRemoteEndPoint, TcpConnectionHandle pCnxHandle)
 {
     Message           = pMsg;
     MessageLength     = pMsgLength;
     RemoteEndPoint    = pRemoteEndPoint;
     _connectionHandle = pCnxHandle;
 }
Пример #3
0
 /// <summary>
 /// Close a connection.
 /// </summary>
 /// <param name="cnxHandle">Connection to close</param>
 public void KillClient(TcpConnectionHandle cnxHandle)
 {
     try
     {
         if (cnxHandle != null)
         {
             OnCloseMessageReceived(new MessageData(null, 0, cnxHandle.ConnectionClient.Client.RemoteEndPoint, cnxHandle));
             // Stop tcpclient.
             cnxHandle.ConnectionClient.Client.Shutdown(SocketShutdown.Both);
             cnxHandle.ConnectionClient.Client.Close();
             cnxHandle.ConnectionClient.Close();
             // Kill the thread.
             cnxHandle.ConnectionThread.Join(50);
             lock (TcpConnectionHandler)
             {
                 TcpConnectionHandler.Remove(cnxHandle);
             }
             cnxHandle = null;
         }
     }
     catch (Exception ex)
     {
         Logger.Error("Exception raised killing tcpconnectionhandle.", ex);
     }
 }
Пример #4
0
        /// <summary>
        /// Send data.
        /// </summary>
        /// <param name="pConnectioHandle">Network connection to use</param>
        /// <param name="pMsg">Data to send</param>
        /// <returns>Send status</returns>
        public bool Send(TcpConnectionHandle pConnectioHandle, string pMsg)
        {
            UTF8Encoding encoder = new UTF8Encoding();

            byte[] buffer = encoder.GetBytes(pMsg);

            return(this.Send(pConnectioHandle, buffer));
        }
Пример #5
0
        /// <summary>
        /// Handle communication with remote client.
        /// Called by ClientsListener thread.
        /// </summary>
        /// <param name="handle">TcpClient Object</param>
        protected virtual void ReceiveDataFromClient(object handle)
        {
            byte[]              buffer = new byte[Buffer_size];
            byte[]              message;
            int                 bytesRead;
            MessageData         msgData;
            TcpConnectionHandle connectionHandle = (TcpConnectionHandle)handle;

            // Create the tcpClient object to handle communication with the remote client.
            TcpClient     tcpClient    = connectionHandle.ConnectionClient;
            NetworkStream clientStream = tcpClient.GetStream();


            //NetworkStream stream = client.GetStream();
            //Int32 i;
            //Byte[] buffer;
            //String result = string.Empty;
            //do {
            //  buffer = new Byte[128];
            //  i = stream.Read(buffer, 0, buffer.Length);
            //  result += ASCIIEncoding.ASCII.GetString(buffer);
            //} while(stream.DataAvailable);



            while (true)
            {
                bytesRead = 0;

                try
                {
                    // Blocks until a client sends a message.
                    bytesRead = clientStream.Read(buffer, 0, Buffer_size);
                }
                catch
                {
                    // A socket error has occurred.
                    this.KillClient(tcpClient);
                    break;
                }

                if (bytesRead == 0)
                {
                    // The client has disconnected from the server.
                    this.KillClient(tcpClient);
                    break;
                }

                // NOTE : Single data buffer is supported here, better work with a second buffer (stringbuilder ?)
                //        to handle data longuest than 4Kb...

                // Copy message data to correctly sized array.
                message = new byte[bytesRead];
                Array.Copy(buffer, message, bytesRead);
                msgData = new MessageData(message, bytesRead, tcpClient.Client.RemoteEndPoint, connectionHandle);

                // Send event to dispatch the new message.
                this.OnMessageReceived(msgData);
                msgData = null;
            }

            if (!_usePermanentConnection)
            {
                // Close the connection, exit the thread.
                this.KillClient(tcpClient);
            }
        }
Пример #6
0
        /// <summary>
        /// Thread that wait for a connection.
        /// </summary>
        protected void ClientsListener()
        {
            try
            {
                TcpConnectionHandle connectionHandle = null;

                try
                {
                    _tcpListener.Start();
                }
                catch (Exception ex)
                {
                    _LastException = ex;
                    _isRunning     = false;
                    return;
                }

                _isRunning = true;

                while (true)
                {
                    TcpClient client;
                    try
                    {
                        // Blocks until a client has connected to the server.
                        client = _tcpListener.AcceptTcpClient();
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Exception raised accepting tcp client connection.", ex);
                        break;
                    }

                    // If the whitelist is used only whitelisted IP address is allowed.
                    if (_useWhitelist && !this.IsWhitelisted(((IPEndPoint)client.Client.RemoteEndPoint).Address))
                    {
                        this.KillClient(client);
                        continue;
                    }

                    // If the blacklist is used blacklisted IP address is rejected.
                    if (_useBlacklist && this.IsBlacklisted(((IPEndPoint)client.Client.RemoteEndPoint).Address))
                    {
                        this.KillClient(client);
                        continue;
                    }

                    // Create a thread to handle communication with connected client.
                    Thread clientThread = new Thread(new ParameterizedThreadStart(ReceiveDataFromClient));
                    clientThread.Name = "TcpReceiver";

                    connectionHandle = new TcpConnectionHandle(clientThread, client);

                    //if (_usePermanentConnection)
                    //{
                    //    // Keep a track of active thread.
                    //    _connectionList.Add(connectionHandle);
                    //}

                    byte[] tmp = BitConverter.GetBytes(clientThread.ManagedThreadId);
                    OnNewConnection(new MessageData(tmp, tmp.Length, client.Client.RemoteEndPoint, connectionHandle));

                    clientThread.Start(connectionHandle);
                    client = null;
                    tmp    = null;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception raised in client listener.", ex);
            }
        }
Пример #7
0
 /// <summary>
 /// Send data.
 /// </summary>
 /// <param name="pConnectioHandle">Network connection to use</param>
 /// <param name="pMsg">Single byte to send</param>
 /// <returns>Send Status</returns>
 public bool Send(TcpConnectionHandle pConnectioHandle, byte pMsg)
 {
     return(this.Send(pConnectioHandle, new byte[] { pMsg }));
 }