Click here to Skip to main content
15,886,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I developed a application which is communicating between server and client via socket with SSL and it works well, but the problem is, unable to hold the connectivity between server and client is more than a 20 min. Very quickly the connection is disabling, unable to listen the server continuously. Client is facing this issue, could some give me the solution for this and I enclosed my project as attachment.

How to hold the server socket connection continuously without closing?

Please give me a solution ASAP. Its urgent.

I am using TcpListener and TcpClient for communication.

Thanks in advance

Gurumoorthy

----------
Server
---------
XML
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
using System.Xml;
using BIPOServerWindowsService.BLL;
using BIPOServerWindowsService.Model;
using Timer = System.Timers.Timer;

namespace BIPOServerWindowsService
{
    /// <summary>
    ///     Class BIPOServer.
    /// </summary>
    public partial class BIPOServer : ServiceBase
    {
        private static System.Timers.Timer _aTimer;
        private string _strCertificateFile = AppDomain.CurrentDomain.BaseDirectory + "BIPOCERT.PFX";

        private string _strFileExtension = DateTime.Now.Hour + "" + DateTime.Now.Minute + "" + DateTime.Now.Second + ".xml";

        private string _strXmlRequestFilesPath = AppDomain.CurrentDomain.BaseDirectory + @"\RequestXMLFile";
        private string _strXmlResponseFilesPath = AppDomain.CurrentDomain.BaseDirectory + @"\ResponseXMLFile";
        private List<Users> _userList = new List<Users>();
        X509Certificate2 _certificate;
        private DataTable _dtCustomerDetails = new DataTable();
        private int _intPortnumber;
        private bool _isAddedNewClient;

        /// <summary>
        ///     The is normal exit
        /// </summary>
        private bool _isNormalExit;

        TcpClient _myClient;
        private TcpListener _myList;
        private int _nUpdatedPorts;
        private MbipoCommunication _objMbipoCommunication = new MbipoCommunication();
        private string _serverIp = string.Empty;
        SslStream _sslStream;
        private string _strApplicationAckCode = string.Empty;
        private int _strApplicationErrorCode;

        /// <summary>
        ///     Initializes a new instance of the <see cref="BIPOServer" /> class.
        /// </summary>
        public BIPOServer()
        {
            InitializeComponent();
        }

        /// <summary>
        ///     When implemented in a derived class, executes when a Start command is sent to the service by the Service Control
        ///     Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to
        ///     take when the service starts.
        /// </summary>
        /// <param name="args">Data passed by the start command.</param>
        protected override void OnStart(string[] args)
        {

            StartServer();
        }

        /// <summary>
        ///     Starts the server.
        /// </summary>
        private void StartServer()
        {
            try
            {
                Debugger.Launch();
                try
                {
                    _certificate = new X509Certificate2(_strCertificateFile, "BIPO");
                    DateTime strExpDate = _certificate.NotAfter; //Getting the Validity Date & Time
                    DateTime strCurrentDate = DateTime.Now; //Getting Current Date & Time
                    if (strExpDate < strCurrentDate) // Validating the Date & Time
                    {
                        BipoConstants.Bindtransactionlog(BipoConstants.CertificateExpired + ". ( " + strExpDate + " )",
                            BipoConstants.BipoErrorTypes.Certificationexpired, BipoConstants.Failed);
                        return;
                    }
                    ServicePointManager.ServerCertificateValidationCallback += OnRemoteCertificateValidationCallback;
                }
                catch (Exception ex)
                {
                    BipoConstants.Bindtransactionlog(ex.Message, BipoConstants.BipoErrorTypes.Certificationfailed,
                        BipoConstants.Failed);
                    return;
                }
                _aTimer = new Timer();
                // Hook up the Elapsed event for the timer.
                _aTimer.Elapsed += _aTimer_Elapsed;
                // Only raise the event the first time Interval elapses.
                _aTimer.Interval = 10000;
                //_aTimer.AutoReset = true;
                _aTimer.Enabled = true;

            }
            catch (Exception exp)
            {
                BipoConstants.Bindtransactionlog(exp.Message, BipoConstants.BipoErrorTypes.Networkconnection,
                    BipoConstants.BipoErrorTypes.Socketconnection);
            }
        }

        private void _aTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                var objMbipoCommunicationNew = new MbipoCommunication
                {
                    AppUserId = BipoConstants.IntAppUserId,
                    PortNumber = string.Empty,
                    IpAddress = string.Empty
                };
                _dtCustomerDetails = BbipoCommunications.BCustomerDetails_Select(objMbipoCommunicationNew);
                if (_nUpdatedPorts < _dtCustomerDetails.Rows.Count)
                    _isAddedNewClient = true;

                if (!_isAddedNewClient) return;
                for (int i = _nUpdatedPorts; i <= _dtCustomerDetails.Rows.Count - 1; i++)
                {
                    _serverIp = _dtCustomerDetails.Rows[i][3].ToString();
                    _intPortnumber = Convert.ToInt32(_dtCustomerDetails.Rows[i][4]);
                    _myList = new TcpListener(IPAddress.Parse(_serverIp), _intPortnumber);
                    try
                    {
                        _myList.Start();

                        var mythread = new Thread(SListenClient);
                        mythread.Start();

                    }
                    catch (Exception ex)
                    {

                        return;
                    }
                }
                GetAllPorts();
                _nUpdatedPorts = _dtCustomerDetails.Rows.Count;
            }
            catch (Exception exp)
            {
                BipoConstants.Bindtransactionlog(exp.Message, BipoConstants.BipoErrorTypes.Networkconnection,
                    BipoConstants.Failed);
            }
        }

        /// <summary>
        ///     Receives the data.
        /// </summary>
        /// <param name="userState">State of the user.</param>
        /// <param name="sslstramMessage"></param>
        private void ReceiveData(object userState, SslStream sslstramMessage)
        {
            var objMbipoCommunication = new MbipoCommunication();
            var user = (Users)userState;
            TcpClient client = user.Client;


            while (true)
            {
                try
                {
                    string receiveString = ReadMessage(sslstramMessage);

                }
                catch (Exception)
                {
                    RemoveUser(user);
                    break;
                }
            }
        }


        /// <summary>
        ///     Sends to client.
        /// </summary>
        private void SendToClient(SslStream sslStreamAck, string strAckMessageResponse)
        {
            byte[] strAcKmessage = Encoding.Default.GetBytes(strAckMessageResponse);
            sslStreamAck.Write(strAcKmessage);
            sslStreamAck.Flush();
        }

        /// <summary>
        ///     Removes the user.
        /// </summary>
        /// <param name="user">The user.</param>
        private void RemoveUser(Users user)
        {
            _myList.Stop();
            _userList.Remove(user);
            user.Close();
            user.Client.Close();
            _sslStream.Close();
        }

        /// <summary>
        ///     When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control
        ///     Manager (SCM). Specifies actions to take when a service stops running.
        /// </summary>
        protected override void OnStop()
        {
            StopServer();
        }

        /// <summary>
        ///     Stop Server
        /// </summary>
        private void StopServer()
        {
            try
            {
                for (int intUserIndex = _userList.Count - 1; intUserIndex >= 0; intUserIndex--)
                {
                    RemoveUser(_userList[intUserIndex]);
                }
            }
            catch (Exception)
            {
                return;
            }
            _isNormalExit = true;
            var objMbipoCommunication = new MbipoCommunication
            {
                AppUserId = BipoConstants.IntAppUserId,
                PortNumber = string.Empty,
                IpAddress = string.Empty
            };
            DataTable dtCustomerDetails = BbipoCommunications.BCustomerDetails_Select(objMbipoCommunication);
            if (dtCustomerDetails == null) return;
            if (dtCustomerDetails.Rows.Count <= 0) return;
            for (int intRowIndex = 0; intRowIndex <= dtCustomerDetails.Rows.Count - 1; intRowIndex++)
            {
                _intPortnumber = Convert.ToInt32(dtCustomerDetails.Rows[intRowIndex][4]);
                try
                {
                    _myList.Stop();
                    BipoConstants.BindConnectionStoppedLog(_intPortnumber.ToString(CultureInfo.InvariantCulture));
                }
                catch (Exception ex)
                {
                    BipoConstants.Bindtransactionlog(ex.Message, BipoConstants.BipoErrorTypes.Socketconnection,
                        BipoConstants.Failed);
                }
            }
        }

        #region Start Server

        /// <summary>
        ///     Client Validation
        /// </summary>
        private void SListenClient()
        {
            _myClient = null;
            try
            {
                while (true)
                {
                    _myClient = _myList.AcceptTcpClient();
                    if (_myClient == null) continue;
                    _sslStream = ProcessClient(_myClient, _certificate);
                    if (_sslStream == null) continue;
                    if (!_sslStream.IsAuthenticated) continue;
                    var user = new Users(_myClient);
                    //sending HL7 Message
                    SendHl7Message(user, _sslStream);

                    var thread = new Thread(() => ReceiveData(user, _sslStream)) { IsBackground = true };
                    thread.Start();
                    _userList.Add(user);
                }
            }
            catch (Exception ex)
            {
                BipoConstants.Bindtransactionlog(ex.Message, BipoConstants.BipoErrorTypes.Unabletoconnectclient,
                    BipoConstants.Failed);
            }
        }

        /// <summary>
        ///     sListenClient.
        /// </summary>
        private static bool OnRemoteCertificateValidationCallback(object sender, X509Certificate certificate,
            X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return (sslPolicyErrors == SslPolicyErrors.None);
        }

        /// <summary>
        ///     Process Client.
        /// </summary>
        private SslStream ProcessClient(TcpClient client, X509Certificate certificate)
        {
            _sslStream = new SslStream(client.GetStream(), false);
            try
            {
                _sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls |
                                                                    SslProtocols.Tls11 |
                                                                    SslProtocols.Tls12 |
                                                                    SslProtocols.Ssl2 |
                                                                    SslProtocols.Ssl3, true);
            }
            catch (AuthenticationException)
            {
                _sslStream.Close();
                client.Close();
                _sslStream = null;
            }
            return _sslStream;
        }
   #endregion
        /// <summary>
        ///     Read message from stream
        /// </summary>
        /// <param name="sslStream"></param>
        /// <returns></returns>
        private string ReadMessage(SslStream sslStream)
        {
            var strmessageData = new StringBuilder();
            try
            {
                // Read the  message sent by the Client.
                var buffer = new byte[1024000];
                int bytes = sslStream.Read(buffer, 0, buffer.Length);
                Decoder decoder = Encoding.Default.GetDecoder();
                var chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                strmessageData.Append(chars);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return strmessageData.ToString();
        }


    }
}
Posted
Updated 28-Jan-14 21:43pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900