c# - TcpClient - 现有连接被远程主机强行关闭

标签 c# tcpclient tcplistener

信息

我一直在用 C# 开发 Web http 服务器,并决定添加远程控制台功能。可以从任何位置使用控制台,并使用 TcpListener(Web 服务器)和 TcpClient(远程控制台)发送命令和函数。

代码

这是我的服务器的样子:

TcpListener consoleListener = new TcpListener(consolePort);
consoleListener.Start();
byte[] bytes = new Byte[256];
string data = null;
while (true)
{
    TcpClient client = consoleListener.AcceptTcpClient();
    data = null;
    byte[] msg = { 0 };
    int i;
    while ((i = client.GetStream().Read(bytes, 0, bytes.Length)) != 0)
    {
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
        if (data == "shutdown")
        {
            //Server shutdown logic.
        }
        //Other commands here...
        else
        {
            msg = Encoding.ASCII.GetBytes("Invalid command. Type 'help' or '?' to get a list of commands.");
        }
        client.GetStream().Write(msg, 0, msg.Length); //sends return message to console
    }
    client.Close(); //closes connection between client and server after EVERY command. Connection is reopened when a new command is sent.
}

注意 - 服务器在网络服务器和主控制台应用程序线程的单独线程上运行。

这是我的客户:

public static string Communicate(string text)
{
    try
    {
        TcpClient client = new TcpClient(ip, port); //initializes tcpclient (ip and port are correct)

        byte[] data = System.Text.Encoding.ASCII.GetBytes(text); //converts text to bytes for stream writing

        NetworkStream stream = client.GetStream();

        stream.Write(data, 0, data.Length);

        Console.WriteLine("Sent data: " + text);

        data = new Byte[256];

        string responseData = String.Empty; //initializes responsData string

        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        client.Close();
        return responseData; //returns what server writes
    }
    catch (Exception ex)
    {
        return "An error occured\n" + ex.ToString();
    }
}

问题

我可以向服务器发送一条命令并成功返回。但是,当我尝试发送另一个命令时,服务器抛出以下错误:

System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at ---.Server.ConsoleListener() in X:\Users\---\Documents\Visual Studio 2013\Projects\---\---\Program.cs:line x

我知道这不是防火墙或管理员提升问题,因为我可以成功发送一个命令。只有在发送第二个命令时才会抛出此错误。

这是描述问题的屏幕截图: The remote console and server communication and error reporting.

编辑:通过做一些研究,我发现问题很可能是我的 for 循环中的一个小错误造成的。但是,我不知道解决这个问题的任何方法,因为我不知道确切的问题:)。请帮助我识别它,以便我修复它。

再次感谢

最佳答案

您的客户端似乎在一条消息后关闭了连接。

responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
client.Close();
return responseData; //returns what server writes

如果你想保持连接,你应该在客户端有一个类似于你在服务器上的循环。如果你想每次都建立一个新的连接,你应该在服务器上优雅地关闭流并且没有这样的循环。如果消息较长或者您需要为命令指定最大长度,您仍然需要循环。

关于c# - TcpClient - 现有连接被远程主机强行关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24767184/

相关文章:

c# - 尝试创建HttpWebRequest时,System.dll中发生了 'System.UriFormatException'类型的未处理异常

c# - 仅将 int 的 json 中的 "null"替换为 "0"还是使用 Nullable<int>?

java - 当 Activity 发生变化时,如何保持与服务器的 TCP 连接?

Android TCP 客户端在 TextView 中读取套接字

java - 在 TCP Client 中从服务器接收消息并在 TextView 中设置它

python - 如何使用 Python 脚本检查特定端口是否正在监听?

c# - asp.net mvc 4 中静态类的替代方法是什么?

c# - HTTP 错误 404.13 - 未找到

c# - Windows 服务中的 TCP IP 监听器

C#多线程文件传输使用TCP