的信息的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