的信息的TcpClient - 一个现有的连接被强行远程主机
我一直在开发C#中的网页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
我知道这是不是防火墙或管理员海拔问题,我可以通过成功地发送一个命令。只有在发送第二个命令时才会抛出此错误。
这里是描述问题的屏幕截图:
编辑:这样做了一些研究,我发现这个问题是最有可能的一个小错误,在我的for循环的结果。但是,我不知道解决这个问题的任何方法,因为我不知道确切的问题:)。请帮助我确定它,以便我可以修复它。
再次感谢
作为便笺:TCP并不保证您将在一次读取中获得*,例如“关闭”*。它可能被分成*“关闭”*和*“下”*。 – EZI
@EZI感谢您的提示 - 我会马上更新! – rodit
@EZI我应该如何实现 - 对不起 – rodit