WinForms error: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

0

I have a small WinForm application. All it does is it reads the message recieved in the buffer. If the message matches the expected keyword, it increases the number shown on the Main window and shows the message in a separate message box. Firewall is off, no 3rd party antivirus or firewall installed, operating system is Windows Server 2019 Datacenter(ver1809).

It runs perfectly but after 2-3 hours it crashes.

Program.cs:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace SocketTestApp
{
    static class Program
    {
        private static SocketTestAppReciever app;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            app=new SocketTestAppReciever();
            app.ShowIcon = false;

            try
            {
                Application.Run(app);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ExceptionToString(ex));
                app.BackColor = System.Drawing.Color.Red;
                Environment.Exit(1);
            }
        }

        public static string ExceptionToString(Exception ex)
        {
            string result = "";
            string tab = "";
            result += "-----------------------------------------------------------------------------\n";

            result += ('\n');

            while (ex != null)
            {
                result += tab + (ex.GetType().FullName) + '\n';
                result += tab + ("Message : " + ex.Message) + '\n';
                result += tab + ("StackTrace : " + ex.StackTrace) + '\n';
                result += tab + ("TargetSite : " + ex.TargetSite.ToString()) + '\n';

                ex = ex.InnerException;
                tab += "    ";
            }
            result += "\n-----------------------------------------------------------------------------\n";
            return result;
        }
        public static void StartListener()
        {
            IPAddress ip = null;
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress _ip in host.AddressList)
            {
                if (_ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip = _ip;
                }
            }
            
            if (ip is null)
            {
                MessageBox.Show("IP is null,exiting", "TestApp StartListener Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Environment.Exit(1);
            }

            TcpListener server = new TcpListener(ip, 8081);

            try
            {
                server.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "TestApp StartListener Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Environment.Exit(1);
            }

            while (true)
            {
                
                TcpClient client = server.AcceptTcpClient();
                NetworkStream stream = client.GetStream();

                try
                {
                    if (stream.CanRead)
                    {
                        byte[] myReadBuffer = new byte[100];
                        StringBuilder myCompleteMessage = new StringBuilder();
                        int numberOfBytesRead = 0;

                        // Incoming message may be larger than the buffer size.
                        do
                        {
                            numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);
                            myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
                        }
                        while (stream.DataAvailable);

                        if (app.ShowEveryMsgInBox) { MessageBox.Show(myCompleteMessage.ToString(), "Message recieved", MessageBoxButtons.OK); }
                        if (myCompleteMessage.ToString() == "LIQUIDATE"){app.IncreaseNumber();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Sorry.  You cannot read from this NetworkStream.", "TestApp StartListener Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        Environment.Exit(1);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString(), "TestApp StartListener error inside wile loop", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Environment.Exit(1);
                }
                finally{stream.Close();}
            }
        }
    }
}

Form1.cs:

using System;
using System.Windows.Forms;
using System.Threading;

namespace SocketTestApp
{
    public partial class SocketTestAppReciever : Form
    {
        public bool ShowEveryMsgInBox=false;
        public SocketTestAppReciever()
        {
            InitializeComponent();
            ShowEveryMsgInBox_checkBox1.CheckedChanged += CheckedChange;
            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;
                Program.StartListener();
            }).Start();
        }

        private void CheckedChange(object sender, EventArgs e)
        {
            ShowEveryMsgInBox = ((CheckBox)sender).Checked;
        }

        public void IncreaseNumber()
        {
            this.Invoke((MethodInvoker)delegate
            {
                label1.Text = (Int32.Parse(this.label1.Text) + 1).ToString();
            });
        }
    }
}

Error message:

System.IO.IOException Message : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. StackTrace : at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at SocketTestApp.Program.d__5.MoveNext()

TargetSite : Int32 Read(Byte[], Int32, Int32) System.Net.Sockets.SocketException

Message : An existing connection was forcibly closed by the remote host

StackTrace : at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) TargetSite : Int32 Read(Byte[], Int32, Int32)

This is what I found in the EventViewer:

Faulting application name: SocketServer.exe, version: 1.0.0.0, time stamp: 0xfb692933 Faulting module name: KERNELBASE.dll, version: 10.0.17763.1518, time stamp: 0xff301d3c Exception code: 0xe0434352 Fault offset: 0x00000000000396c9 Faulting process id: 0x22064 Faulting application start time: 0x01d6ac886ca804ae Faulting application path: C:\Users\paperspace\Desktop\SocketServer.exe Faulting module path: C:\Windows\System32\KERNELBASE.dll Report Id: e469e9f9-8f5c-4597-8c4c-5ba4ac06c6bb Faulting package full name: Faulting package-relative application ID:

Could you please help me with the issue? I am new to programming and have no idea what exactly closed it. Is the remote host the operating system? Or can someone else just randomly close this connection?

c#
tcp
tcpclient
tcplistener
asked on Stack Overflow Oct 21, 2020 by RLaszlo • edited Oct 27, 2020 by RLaszlo

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0