Click here to Skip to main content
15,887,027 members
Home / Discussions / .NET (Core and Framework)
   

.NET (Core and Framework)

 
AnswerRe: online payment Pin
Pete O'Hanlon23-Jun-09 21:38
mvePete O'Hanlon23-Jun-09 21:38 
AnswerRe: online payment Pin
Baran M24-Jun-09 2:16
Baran M24-Jun-09 2:16 
QuestionSystem Context Menu (Restore,Maximize,Close etc.) on part of client area Pin
pimb223-Jun-09 2:40
pimb223-Jun-09 2:40 
AnswerRe: System Context Menu (Restore,Maximize,Close etc.) on part of client area Pin
Eddy Vluggen25-Jun-09 8:44
professionalEddy Vluggen25-Jun-09 8:44 
GeneralRe: System Context Menu (Restore,Maximize,Close etc.) on part of client area Pin
pimb225-Jun-09 8:47
pimb225-Jun-09 8:47 
GeneralRe: System Context Menu (Restore,Maximize,Close etc.) on part of client area Pin
Eddy Vluggen25-Jun-09 9:11
professionalEddy Vluggen25-Jun-09 9:11 
AnswerRe: System Context Menu (Restore,Maximize,Close etc.) on part of client area Pin
pimb210-Jul-09 4:09
pimb210-Jul-09 4:09 
QuestionHow to check if TcpClient is connected to server? [modified] Pin
s_stoqnov23-Jun-09 0:45
s_stoqnov23-Jun-09 0:45 
Hello,

I made a server and client side application. Communication between them is through tcp/ip.
Server application (tcp server) is developed in Delphi 7 using Indy 9.
Client application is developed in VS2005 using CF.NET 2.0.

I want to find if connection between the server and the client is lost.

As far I read, the only way to know if the client has been disconnected is to write or read from the socket.
But it is not working. When the client is disconnected i try to send/read data to and from then network stream.
But no exception is raised or any other indication to sense that the client has been disconnected.

Even if the server is not started, when i try to connect no exception is raised.

Here is my code (Connect, ReadData and SendData functions):

///summary;
        /// Get a readble and writable network stream.
        /// </summary>
        /// <param name="AWait">How long to wait for the network stream.</param>
        /// <returns>Returns the network stream of the current tcp connection.</returns>
        private NetworkStream GetStream(int AWait)
        {
            //if (!Connected && !Connect(_host, _port))
            //    throw new Exception(string.Format("GetStream(): Can not connect to host \"{0}:{1}", _host, _port));

            NetworkStream ns = _tcp.GetStream();

            int time = Environment.TickCount;

            while (true)
            {
                if (ns.CanRead && ns.CanWrite) break;
                if (Environment.TickCount - time >= AWait)
                    throw new Exception("Unable to get NetworkStream. TIMEOUT!!!", new SocketException());
            }

            return ns;
        }

        ///summary>
        /// Gets data from TCP stream. Data is verified for ACK SOH DATA EOT.
        /// On error exception is thrown.
        /// </summary>
        /// <param name="Data">Read data is written at the StringBuilder.</param>
        /// <returns>On success return true.</returns>
        protected bool GetData(StringBuilder Data)
        {
            Debug.WriteLine("GET DATA");
            if (!Connected)
            {
                Debug.WriteLine("GET DATA: NOT CONNECTED");
                this._error = "GetData: Not connected.";
                return false;
            }

            int cnt = 0, i = 0, start = 0;
            bool Done = false;
            bool ACKFlag = false, SOHFlag = false, EOTFlag = false;
            string PartialStr = String.Empty;
            DateTime dt = DateTime.Now.AddSeconds(10);

            byte[] buffer = new byte[_tcp.ReceiveBufferSize];

            NetworkStream ns = GetStream(10000);
            //ns.ReadTimeout = 100;
            
            do
            {
                Debug.WriteLine("GetData: LOOP");
                //ns.Read(buffer, 0, 1);

                if (!ns.CanRead) throw new Exception("Can't read from network stream.");
                //if (!ns.DataAvailable) continue;

                cnt++;

                buffer.Initialize();

                int bytes;
                try
                {
                    bytes = ns.Read(buffer, 0, _tcp.ReceiveBufferSize);
                    Debug.WriteLine("Received " + bytes + " bytes");
                }
                catch
                {
                    Debug.WriteLine("read timeout");
                    continue;
                }

                while (buffer[i] != 0)
                {
                    // Don't scan more than what is read.
                    if (i + 1 > bytes) break;

                    // След като клиента е пратил команда към сървъра,
                    // сървъра като първи байт връща ACK или NAK.
                    ACKFlag = (ACKFlag || (buffer[i] == (byte)SEPARATOR.ACK));
                    Debug.WriteLineIf(buffer[i] == (byte)SEPARATOR.ACK, "ACK");

                    // След което за начало на данните сървъра праща SOH
                    SOHFlag = (SOHFlag || (buffer[i] == (byte)SEPARATOR.SOH));
                    Debug.WriteLineIf(buffer[i] == (byte)SEPARATOR.SOH, "SOH");

                    // За край на данните, сървъра праща EOT
                    EOTFlag = (EOTFlag || (buffer[i] == (byte)SEPARATOR.EOT));
                    if (EOTFlag) Debug.WriteLine("EOT");
                    if ((ACKFlag) && (EOTFlag)) break;

                    if (buffer[i] == (byte)SEPARATOR.NAK)
                    {
                        _error = Data.ToString();

                        int b; string tmp = string.Empty;
                        for (int k = 0; k < _error.Length; k++)
                        {
                            b = (int)_error[k];
                            if (b == (byte)SEPARATOR.US)
                                tmp += "\r\n";
                            if ((b >= 32) || (b == 0x0A) || (b == 0x0D))
                                tmp += _error[k];
                        }

                        _error = /*"Server responded with NAK.\r\n" + */ tmp;

                        Debug.WriteLine(_error);
                        return false;

                        /*string tmp = string.Empty;
                        if (i >= 1)
                            _error = Encoding.GetEncoding(1251).GetString(buffer, 0, i);

                        int b;
                        */
                    }

                    // Чакаме ACK и SOH
                    if (/*ACKFlag &&*/ SOHFlag)
                    {
                        if (buffer[i] == (byte)SEPARATOR.STX)
                        {
                            start = i;
                        }

                        if (buffer[i] == (byte)SEPARATOR.ETX)
                        {
                            //if (i == (start + 1)) continue;

                            PartialStr = System.Text.Encoding.GetEncoding(1251).GetString(buffer, start, i - start + 1);
                            Data.Append(PartialStr);

                            Debug.Write("STX ");
                            Debug.WriteLine(PartialStr.Substring(1, PartialStr.Length - 2) + " ETX");
                        }
                    }
                    i++;
                }

                Done = (ACKFlag && EOTFlag);
                dt = DateTime.Now.AddSeconds(10);
            }
            while ((dt > DateTime.Now) && !Done);

            Debug.WriteLine(cnt + " iterations.");

            if (!Done) _error = "TIMEOUT!!!";
            if (!Done && !EOTFlag) _error = "Incomplate package has been received. EOT not received.";

            return Done;
        }

        /// <summary>
        /// Send data through TCP stream.
        /// On error exception is thrown.
        /// </summary>
        /// <param name="Data">Data to be send.</param>
        /// <returns>On success return true.</returns>
        protected bool SendData(ArrayList Data)
        {
            Debug.WriteLine("SEND DATA");

            if (!Connected)
            {
                Debug.WriteLine("SEND DATA: NOT CONNECTED");
                this._error = "SendData: Not connected.";
                return false;
            }

            NetworkStream ns = GetStream(10000);

            byte[] buffer = new byte[_tcp.ReceiveBufferSize];
            try
            {
                // Clear the input buffer
                if (ns.DataAvailable) 
                {
                    Debug.WriteLine("SEND DATA: CLEAR INPUT BUFFER");
                    ns.Read(buffer, 0, _tcp.ReceiveBufferSize); 
                }
            }
            catch 
            { 
            }

            Data.Insert(4, (byte)SEPARATOR.SOH);
            Data.Add((byte)SEPARATOR.EOT);

            byte[] b = (byte[])Data.ToArray(typeof(byte));
            ns.Write(b, 0, b.Length);

            Debug.WriteLine("SEND DATA: send " + b.Length.ToString() + " bytes.");

            return true;
        }

        /// <summary>
        /// Connect to the host computer.
        /// </summary>
        /// <returns>Returns true on success.</returns>
        public bool Connect()
        {
            if ((this._host == "") || (this._port == 0)) { return false; }

            try
            {
                if ((SystemState.ConnectionsNetworkCount <= 0) &&
                    (!SystemState.CradlePresent))
                {
                    Disconnect();

                    _error = ResourceManager.Instance.GetString("s_NoWireless");
                    Debug.WriteLine("NO WIRELESS");
                    return false;
                }

                try
                {
                    Debug.WriteLine("PING TO HOST");
                    //byte[] b = BitConverter.GetBytes((int)COMMAND.PING);
                    //GetStream(1000).Write(b, 0, b.Length);

                    _connected = PING();
                    if (!_connected) Disconnect();
                }
                catch
                {
                    Debug.WriteLine("EXCEPTION: NOT CONNECTED");
                    Disconnect();
                }

                if (!Connected)
                {
                    Debug.WriteLine(string.Format("CONNECT TO HOST {0}:{1}", _host, _port));

                    if (this._tcp == null) { this._tcp = new TcpClient(); }
                    this._tcp.Connect(this._host, this._port);

                    _connected = true;
                    //this._connected = (_tcp.Client.Poll(1, SelectMode.SelectWrite) &&
                    //    _tcp.Client.Poll(1, SelectMode.SelectRead) && !_tcp.Client.Poll(1, SelectMode.SelectError)) ? true : false;
                    Debug.WriteLineIf(!_connected, "Poll says: NOT CONNECTED");
                    
                    if (Connected)
                    {
                        try
                        {
                            Debug.WriteLine("PING TO HOST");
                            _connected = PING();
                            if (!_connected) Disconnect();
                        }
                        catch
                        {
                            Debug.WriteLine("EXCEPTION: NOT CONNECTED");
                            Disconnect();
                        }
                    }
                    else
                    {
                        _connected = false;
                        //_error = ResourceManager.Instance.GetString("s_NoConnection");
                        //_error = String.Format(_error, _host, _port);
                        _error = "Can't connect to server.\r\n";
                        Debug.WriteLine(_error);
                    }

                    //this._connected = _tcp.Client.Poll(1, SelectMode.SelectWrite) &&
                    //    _tcp.Client.Poll(1, SelectMode.SelectRead) && !_tcp.Client.Poll(1, SelectMode.SelectError) ? true : false;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("CATCH EXCEPTION");
                //_error = ResourceManager.Instance.GetString("s_NoConnection");
                //_error = String.Format(_error, _host, _port);
                _error += e.StackTrace + "\r\n" + e.Message;

                Disconnect();

                TMessageList.AddMessage("Connect() > ", e);
            }

            return Connected;
        }

        private bool PING()
        {
            bool res = false;

            try
            {
                ClearDataBuffer();
                _result.Length = 0;

                AddNumberToDataBuffer((int)COMMAND.PING);

                AddSeparatorToDataBuffer(SEPARATOR.STX);
                AddStringToDataBuffer(GSC.DeviceId);
                AddSeparatorToDataBuffer(SEPARATOR.ETX);

                AddSeparatorToDataBuffer(SEPARATOR.STX);
                AddASCIINumberToDataBuffer(GSC.TermialNumb);
                AddSeparatorToDataBuffer(SEPARATOR.ETX);

                res = SendData(_data);
                if (res)
                {
                    res = GetData(_result);
                }
            }
            catch
            {
                res = false;
            }
            finally
            {
                ClearDataBuffer();
                _result.Length = 0;
            }

           return res;
        }


Stanislav Stoqnov

modified on Tuesday, June 23, 2009 7:51 AM

AnswerRe: How to check if TcpClient is connected to server? Pin
s_stoqnov23-Jun-09 2:42
s_stoqnov23-Jun-09 2:42 
AnswerRe: How to check if TcpClient is connected to server? Pin
supercat924-Jun-09 5:49
supercat924-Jun-09 5:49 
QuestionCrystal Report Pin
Bahram.Zarrin22-Jun-09 11:06
Bahram.Zarrin22-Jun-09 11:06 
QuestionThree tier architecture, database access layer pattern [modified] Pin
Julen21-Jun-09 2:35
Julen21-Jun-09 2:35 
AnswerRe: Tree tier architecture, database access layer pattern Pin
Eddy Vluggen21-Jun-09 3:31
professionalEddy Vluggen21-Jun-09 3:31 
QuestionRe: Tree tier architecture, database access layer pattern Pin
Julen21-Jun-09 3:56
Julen21-Jun-09 3:56 
AnswerRe: Tree tier architecture, database access layer pattern Pin
Eddy Vluggen21-Jun-09 5:19
professionalEddy Vluggen21-Jun-09 5:19 
AnswerRe: Tree tier architecture, database access layer pattern Pin
vasanth111122-Jun-09 0:55
vasanth111122-Jun-09 0:55 
GeneralRe: Tree tier architecture, database access layer pattern Pin
Eddy Vluggen22-Jun-09 12:24
professionalEddy Vluggen22-Jun-09 12:24 
AnswerRe: Tree tier architecture, database access layer pattern Pin
PIEBALDconsult22-Jun-09 7:46
mvePIEBALDconsult22-Jun-09 7:46 
QuestionRe: Tree tier architecture, database access layer pattern Pin
Julen22-Jun-09 11:15
Julen22-Jun-09 11:15 
AnswerRe: Tree tier architecture, database access layer pattern Pin
Eddy Vluggen23-Jun-09 0:14
professionalEddy Vluggen23-Jun-09 0:14 
AnswerRe: Tree tier architecture, database access layer pattern [modified] Pin
Dave Kreskowiak21-Jun-09 8:05
mveDave Kreskowiak21-Jun-09 8:05 
QuestionRe: Tree tier architecture, database access layer pattern Pin
Julen21-Jun-09 21:41
Julen21-Jun-09 21:41 
AnswerRe: Tree tier architecture, database access layer pattern Pin
Shukla Rahul21-Jun-09 23:54
Shukla Rahul21-Jun-09 23:54 
QuestionRe: Three tier architecture, database access layer pattern Pin
Julen22-Jun-09 0:03
Julen22-Jun-09 0:03 
AnswerRe: Three tier architecture, database access layer pattern Pin
Shukla Rahul22-Jun-09 2:40
Shukla Rahul22-Jun-09 2:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.