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

2

6

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!

Bik answered 18/5, 2015 at 19:34 Comment(2)
I meant send the results to the client. I simply wanted to make a simple server that would recieve keywords amd then run the appropriate function. The results should be able to be sent back. I think I may have implimented this wrong so any help is appreciated.Bik
It might also be causing by #43186855Christmann
P
1

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

Psalms answered 3/6, 2015 at 6:56 Comment(5)
Is therr a way to have it not close it prematurely? Ive removed the closes but it still seems to hang,Bik
or even netter just have it loop and make sure it has read all the data first?Bik
If you simply remove close() then the client exits prematurely anyway. You need to make the client aware (implicitly or explicitly) of the server's intention to finish the exchange. In an implicit implementation you could make the client ask the server for a response a predetermined number of times (you can see a naive way to do it in my screenshot). And an explicit method of doing it would be to make the server send a special message to the client, so that until such a message is received, the client keeps waiting for the server's response.Psalms
well I changed the if statement to a while but I need to figire out how to then stop at a certain string tag likr <eof>Bik
Compare it? Sorry, I don't see how it's a problem to just if (response == "<eof>") break; . And you can add an outer loop that would ask the user to enter another command, for example.Psalms
N
-2

The error message is typical for when a TCP connection times out. If you issue a new command against that connection, you will often receive this error message. You may have to be able to handle problems with the connections.

Niela answered 18/5, 2015 at 19:39 Comment(7)
What in the OP's question leads you to believe this has any thing to do with a SQL connection?Ostrander
Client server communication via TCP sockets ... very common issue.Niela
Aye, its so common that its hard to find much in the way of answers. Just about every .net site has this issue in one way or another but not much in the way of answering my specific problem. Any idea where I may be going wrong? From the error I can only assume that for whatever reason i have dropped the connection or lost it but im at a total lost where or how I ended up doing that.Bik
@MarcJohnston - I get what the question is. I just don't see why you're bringing SQL connection time outs into it...Ostrander
Well now that its cleared up we are talking about TCP socket issues, what would you recommend I change or add to fix this problem? Some code changes are in order but im seriously at a loss here.Bik
Concentrate on a prototype of TCP client and server. Remove all other business logic. Ensure both the client and the server are capable of handling timeouts and disconnects. Then reintegrate that back into your app. I'd also recommend looking for sample apps that already have the basic plumbing of the TCP server and client done, tested and working.Niela
Thats exactly what I did, this works fine, even after the exception it can still take commands, but for some reason it loses the connection on the stream when asked to ping sweet. Could you take a look at the code and offer me something I can use?Bik

© 2022 - 2024 — McMap. All rights reserved.