我似乎无法修复的编程错误:无法将数据写入传输连接

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

我想为这么长的时间道歉 post 但我想确保我提供了获得帮助所需的一切。

错误:无法将数据写入传输连接:主机中的软件中止了已建立的连接。

错误出现在第307行:

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

我尝试过的:

  1. 禁用 AV
  2. 禁用固件(虽然我认为在这种情况下不需要它)
  3. 用 Google 搜索 - 找到了数千个结果,但似乎没有一个能很好地说明如何解决此问题。

重现问题:

  1. 启动服务器
  2. 启动客户端

服务器:

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();
            }
        }
    }
  }
}

客户:

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);
        }

    }
}

感谢大家的帮助!

此错误消息是 TCP 连接超时时的典型错误消息。如果您针对该连接发出新命令,您通常会收到此错误消息。您可能必须能够处理连接问题。

您的客户端只读取一行,然后在服务器发出其余响应之前关闭连接。它按以下顺序排列:

  1. 客户第 34 行(writer.WriteLineAsync("Sweep 192.168.0")
  2. 服务器线路 304 (writer.WriteLineAsync("FromServer: Initiating Sweep"))
  3. 客户端第 36 行(reader.ReadLineAsync()
  4. 客户第 44-46 行(client.Close()
  5. 服务器第307行...但是客户端已经关闭了连接。

解决方法是不要过早关闭连接并等待服务器消息的其余部分。甚至只需再添加两条 ReadLineAsync() 行即可修复它。