Search code examples
c#networkstream

How to restart a Network Stream after a SocketException


I have a piece of code that reads a JSON stream from a server on the public internet. I am trying to make the connection a little more robust by catching the exception and trying to restart it on a given interval but I haven't been able to figure out how to restart it.

My stream code is as follows

TcpClient connection = new TcpClient(hostname, port);
NetworkStream stream = connection.GetStream();

thread = new Thread(ProcessStream);
thread.Start(stream);

My ProcessStream method is

private void ProcessStream(object stream)
{
    Stream source = (NetworkStream)stream;
    byte[] line;
    int count;
    const int capacity = 300;
    ReadState readState;
    while ((readState = ReadStreamLine(source, out line, out count, capacity)) != ReadState.EOF && _stopFeed == false)
    {
        if (readState != ReadState.Error && count > 4)
        {
            byte[] line1 = new byte[count];
            Array.Copy(line, line1, count);
            Process(line1); // return ignored in stream mode                    
        }
        else
        {
            ReadFail(line, count);
        }
    }
}

and my ReadStream function takes the stream s, does an s.ReadByte and then catches the exception when the network connection is broken. It is here that I am not sure how to try and restart the stream on a timed basis. It does not restart automatically when the network is restored.


Solution

  • From what I can tell, you instantiate your TcpClient before you start your method. So, in order to restart your stream, you need to re-instantiate or re-initialize your connection stream before trying again.

    try 
    {
         // Do something
    }
    catch (Exception ex)
    {
        // Caught your exception, might be ideal to log it too
        // Have a count, if count is less than goal
        // Call your method again
        if (count < 5)
        {
            // re-initialize or re-instantiate connection
            TcpClient connection = new TcpClient(host, port);
            NetworkStream stream = connection.GetStream();
            ProcessStream(stream);
        }
    }
    

    I hope this helps.