Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming Error I cant seem to fix: Unable to write data to the transport connection

I want to apologize for the long post but I wanted to make sure I supplied everything needed to get some help.

The Error: Unable to write data to the transport connection: An established connection was aborted by the software in your host machine.

the error appears on line 307:

await writer.WriteLineAsync("FromServer: Scan Completed");

What I have Tried:

  1. Disabled AV
  2. Disabled FW (though I didnt think its needed in this case)
  3. Googled - Found thousands of results but not a single one seemed to shed much light on how to fix this issue.

Reproduce Issue:

  1. Start Server
  2. Start Client

Server:

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;


namespace NCServer
{
    class Program
    {
        /// <summary>
        ///  General GLOBAL strings
        /// </summary>
        public static readonly string AppRoot = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
        public static string curDir = System.Environment.CurrentDirectory;
        public static int i = 1;
        public static string ver = "0.1a";
        public static string xmlsrvr_Ip;
        public static string xmlsrvr_Port;
        public static string xmlsrvr_MaxCon;
        public static string xmldb_dbType;
        public static string xmldb_dbAddress;
        public static string xmldb_dbPort;
        public static string xmldb_dbLogin;
        public static string xmldb_dbPassword;
        public static CountdownEvent countdown;
        public static int upCount = 0;
        public static long completetime;
        public static List<String> ipsup { get; set; }
        public static object lockObj = new object();
        public const bool resolveNames = false;


       ///////////// Functions Start ////////////////////////////////////////////////////
       /// <summary>
       ///  Get your local IP Address
       /// </summary>
       /// <returns>
       ///  local IP Address as string
       /// </returns>
        public static string GetIPAddress()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }

        /// <summary>
        ///  Read the XML config in the CWD of the server
        /// </summary>
        static void readXML()
        {
            XmlTextReader reader = new XmlTextReader(curDir + "/netscanserver.xml");
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element: // The node is an element.
                        break;
                    case XmlNodeType.Text: //Display the text in each element.
                        switch (i)
                        {

                            case 1:
                                i++;
                                xmlsrvr_Ip = reader.Value;
                                break;
                            case 2:
                                i++;
                                xmlsrvr_Port = reader.Value;
                                break;
                            case 3:
                                i++;
                                xmlsrvr_MaxCon = reader.Value;
                                break;
                            case 4:
                                i++;
                                xmldb_dbType = reader.Value;
                                break;
                            case 5:
                                i++;
                                xmldb_dbAddress = reader.Value;
                                break;
                            case 6:
                                i++;
                                xmldb_dbPort = reader.Value;
                                break;
                            case 7:
                                i++;
                                xmldb_dbLogin = reader.Value;
                                break;
                            case 8:
                                i++;
                                xmldb_dbPassword = reader.Value;
                                break;
                        }
                        break;
                    case XmlNodeType.EndElement:
                        break;

                }
            }
        }

        static void pingsweeper(string ipBase)
        {
            countdown = new CountdownEvent(1);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 1; i < 255; i++)
            {
                string ip = ipBase + "." + i.ToString();
                Ping p = new Ping();
                p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
                countdown.AddCount();
                p.SendAsync(ip, 100, ip);
            }
            countdown.Signal();
            countdown.Wait();
            sw.Stop();
            TimeSpan span = new TimeSpan(sw.ElapsedTicks);
            completetime = sw.ElapsedMilliseconds;
        }

        /// <summary>
        ///  Create a Default NON-WORKING xml config
        /// </summary>
        static void createDefaultXML()
        {
            ///// Generic Defaults
            string srvrip = GetIPAddress();
            string srverport = "8000";
            string maxconns = "5";
            string dbtype = "MySQL";
            string dbAddress = "127.0.0.1";
            string dbPort = "3306";
            string dbLogin = "Your_DB_Login";
            string dbPassword = "Your_DB_Password";

            /// Create XML template.
            ///
            XmlTextWriter writer = new XmlTextWriter("netscanserver.xml", System.Text.Encoding.UTF8);
            writer.WriteStartDocument(true);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2;
            writer.WriteStartElement("Settings");
            writer.WriteStartElement("Server_Config");
            writer.WriteStartElement("srvr_Ip_Address");
            writer.WriteString(srvrip);
            writer.WriteEndElement();
            writer.WriteStartElement("srvr_Port");
            writer.WriteString(srverport);
            writer.WriteEndElement();
            writer.WriteStartElement("srvr_MaxConns");
            writer.WriteString(maxconns);
            writer.WriteEndElement();
            writer.WriteStartElement("db_dbType");
            writer.WriteString(dbtype);
            writer.WriteEndElement();
            writer.WriteStartElement("db_dbAddress");
            writer.WriteString(dbAddress);
            writer.WriteEndElement();
            writer.WriteStartElement("db_dbPort");
            writer.WriteString(dbPort);
            writer.WriteEndElement();
            writer.WriteStartElement("db_dbLogin");
            writer.WriteString(dbLogin);
            writer.WriteEndElement();
            writer.WriteStartElement("db_dbPassword");
            writer.WriteString(dbPassword);
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();

        }

        static void p_PingCompleted(object sender, PingCompletedEventArgs e)
        {
            ipsup = new List<String>();
            string ip = (string)e.UserState;
            if (e.Reply != null && e.Reply.Status == IPStatus.Success)
            {
                if (resolveNames)
                {
                    string name;
                    try
                    {
                        IPHostEntry hostEntry = Dns.GetHostEntry(ip);
                        name = hostEntry.HostName;
                    }
                    catch (SocketException ex)
                    {
                        name = "?";
                    }
                    ipsup.Add("Ip:" + ip + " Hostname:" + name + " Reply:" + e.Reply.RoundtripTime);
                }
                else
                {
                    ipsup.Add("Ip:" + ip + " Reply:" + e.Reply.RoundtripTime);
                }
                lock(lockObj)
                {
                    upCount++;
                }
            }
            else if (e.Reply == null)
            {

            }
            countdown.Signal();
        }

        /// <summary>
        /// Start listening for connections
        /// </summary>
        public class StartServer
    {
        public async void Start()
        {
            IPAddress ip = IPAddress.Parse(xmlsrvr_Ip);
            int port = Int32.Parse(xmlsrvr_Port);
            TcpListener listener = new TcpListener(ip, port);
            listener.Start();
            LogMessage("Server is running");

            while (true)
            {
                LogMessage("Waiting for connections...");
                try
                {
                    var tcpClient = await listener.AcceptTcpClientAsync();
                     HandleConnectionAsync(tcpClient);
                }
                catch (Exception exp)
                {
                    LogMessage(exp.ToString());
                }

            }

        }

       ///<summary>
        /// Process Individual clients
        /// </summary>
        ///
        ///
        private async void HandleConnectionAsync(TcpClient tcpClient)
        {
            string clientInfo = tcpClient.Client.RemoteEndPoint.ToString();
            LogMessage(string.Format("Got connection request from {0}", clientInfo));
            try
            {
                using (var networkStream = tcpClient.GetStream())
                using (var reader = new StreamReader(networkStream))
                using (var writer = new StreamWriter(networkStream))
                {
                    writer.AutoFlush = true;
                    while (true)
                    {
                        var dataFromClient = await reader.ReadLineAsync(); //Get text from Client
                        if (string.IsNullOrEmpty(dataFromClient)) // Check for null data
                        {
                            break;
                        }

                        var data = dataFromClient.ToLower(); // make all lowercase
                        Regex r = new Regex("^[a-zA-Z0-9\x20\x2E]+$");
                            if (r.IsMatch(data)) // ensure text is only numbers,text, and spaces
                            {
                                string[] commands = data.Split(' '); //Seperate into commands/ args
                                switch (commands[0]) // 0 = Command 1-inf = args
                                {
                                    case "date":
                                        LogMessage("Date command issued:" + DateTime.Now.ToLongDateString()); // Send to server consule
                                        await writer.WriteLineAsync("FromServer:" + DateTime.Now.ToLongDateString()); /// Send text to client
                                        break;

                                    case "sweep": // 1 = Ip Base.
                                        string ipBase = commands[1];
                                        LogMessage("Sweep command issued:" ); // Send to server consule
                                        await writer.WriteLineAsync("FromServer: Initiating Sweep"); /// Send text to client
                                        // Scan Network by base
                                        //pingsweeper(ipBase);
                                        await writer.WriteLineAsync("FromServer: Scan Completed");
                                        await writer.WriteLineAsync("FromServer: Took " + completetime + "milliseconds." + upCount + "hosts active");

                                        foreach (string value in ipsup)
                                            {
                                             await writer.WriteLineAsync("FromServer: " + value);
                                            }
                                        break;
                                }
                            }
                    }
                }
            }
            catch (Exception exp)
            {
                LogMessage(exp.Message);
            }
            finally
            {
               LogMessage(string.Format("Closing the client connection - {0}",
                        clientInfo));
              tcpClient.Close();
            }

        }
        private void LogMessage(string message,
                                [CallerMemberName]string callername = "")
        {
            System.Console.WriteLine("[{0}] - Thread-{1}- {2}",
                    callername, Thread.CurrentThread.ManagedThreadId, message);
        }

        /// <summary>
        ///  This is the Main program
        /// </summary>
        /// <param name="args">
        ///  Any arguments that may be passed to the application,
        ///  non defined ATM
        /// </param>
        static void Main(string[] args)
        {
                             // string xmlsrvr_Ip;
                            //string xmlsrvr_Port;
                            //string xmlsrvr_MaxCon;
                            //string xmldb_dbType;
                            //string xmldb_dbAddress;
                            //string xmldb_dbPort;
                            //string xmldb_dbLogin;
                            //xmldb_dbPassword;
            string curDir = System.Environment.CurrentDirectory;
            // Banner
            Console.WriteLine("*******************************");
            Console.WriteLine("       Netwatch v." + ver);
            Console.WriteLine("*******************************");
            // Check if xml file exists in current dir.
            if (System.IO.File.Exists(curDir + "/netscanserver.xml"))  //it exists
            {

                Console.WriteLine("Loading config:" + curDir + "/netscanserver.xml");
                readXML();
                Console.WriteLine("Configuration Loaded");
                Console.WriteLine("Starting server on IP:" + xmlsrvr_Ip + ":" + xmlsrvr_Port);
                StartServer async = new StartServer();
                async.Start();
                Console.WriteLine("Press enter to Quit Server");
                Console.ReadKey();
            }
            else   //it does not exist
            {
                Console.WriteLine("Config file not found, creating in " + curDir);
                createDefaultXML();
                Console.WriteLine("Config file written please configure, press ENTER to exit.");
                Console.ReadKey();
            }
        }
    }
  }
}

Client:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NCclient
{
    class Program
    {
        static void Main(string[] args)
        {
            StartClient(8000);
            Console.ReadLine();
        }

        private static async void StartClient(int port)
        {
            TcpClient client = new TcpClient();
            await client.ConnectAsync("192.168.0.137", port); //Server IP
            LogMessage("Connected to Server");
            using (var networkStream = client.GetStream())
            using (var writer = new StreamWriter(networkStream))
            using (var reader = new StreamReader(networkStream))
            {
                writer.AutoFlush = true;
                   await writer.WriteLineAsync("Sweep 192.168.0");  /// Send command
                  // await writer.WriteLineAsync("DaTe");  /// Send command
                    var dataFromServer = await reader.ReadLineAsync();
                    if (!string.IsNullOrEmpty(dataFromServer))
                    {
                        LogMessage(dataFromServer);
                    }

            }
            if (client != null)
            {
                client.Close();
            }

        }
        private static void LogMessage(string message,
                [CallerMemberName]string callername = "")
        {
            System.Console.WriteLine("{0} - Thread-{1}- {2}",
                callername, Thread.CurrentThread.ManagedThreadId, message);
        }

    }
}

Thanks for any and all help guys!

like image 711
Scott Johnson Avatar asked Nov 27 '22 06:11

Scott Johnson


1 Answers

Your client reads only one line and then closes the connection before the server gives out the rest of its response. It goes in the following order:

  1. Client line 34 (writer.WriteLineAsync("Sweep 192.168.0"))
  2. Server line 304 (writer.WriteLineAsync("FromServer: Initiating Sweep"))
  3. Client line 36 (reader.ReadLineAsync())
  4. Client lines 44-46 (client.Close())
  5. Server line 307... but the client has already closed the connection.

The fix is to not close the connection prematurely and to wait for the rest of the server's message. Even simply adding two more ReadLineAsync() lines fixed it.

Client working fine

like image 128
Yegor Avatar answered Dec 16 '22 10:12

Yegor