简体   繁体   中英

Reconnecting to an unclosed Socket connection C#

I have a Listener application which expects a string message for display. I cannot modify this application. I have to send messages to this listener through my C# client. Both the listener and client are supposed to run on the same PC (local host).

My Code to Connect:

    public void ConnectAndSendMessage(string MessageToSend)
    {
        string localIP = GetIPAddress();

        try
        {
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");
            tcpclnt.Connect(localIP, 2400);

            Socket socket = tcpclnt.Client;
            bool connectionStatus = socket.Connected;

            if (connectionStatus)
            {
                //Send Message
                ASCIIEncoding asen = new ASCIIEncoding();
                //string sDateTime = DateTime.Now.ToString();
                int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
            }
            Thread.Sleep(2000);

            tcpclnt.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }

Problem:

The client application runs fine and send the messages successfully to the Listener. But the problem comes if the client gets crashed (I close the client program) before executing tcpclnt.Close(); . In this case, if I restart the Client program again then, I cannot connect to the socket since the application didn't close the socket in the previous run (crashed run).

How can I reconnect to the listener in this condition?

try this one..

public void ConnectAndSendMessage(string MessageToSend)
{
    string localIP = GetIPAddress();

    using (System.Net.Sockets.TcpClient tcpclnt = new System.Net.Sockets.TcpClient())
    {
        try
        {
            Console.WriteLine("Connecting.....");
            tcpclnt.Connect(localIP, 2400);

            using (System.Net.Sockets.Socket socket = tcpclnt.Client)
            {
                if (socket.Connected)
                {
                    //Send Message
                    System.Text.ASCIIEncoding asen = new System.Text.ASCIIEncoding();
                    //string sDateTime = DateTime.Now.ToString();
                    int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
                }
                System.Threading.Thread.Sleep(2000);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
        finally
        {
            if (tcpclnt != null && tcpclnt.Connected)
                tcpclnt.Close();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM