Information
I am developing a web http server in C # and decided to add a remote console function. The console can be used from anywhere and uses TcpListener (web server) and TcpClient (remote console) to send commands and functions through.
The code
This is what my server looks like:
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")
{
}
else
{
msg = Encoding.ASCII.GetBytes("Invalid command. Type 'help' or '?' to get a list of commands.");
}
client.GetStream().Write(msg, 0, msg.Length);
}
client.Close();
}
Note. The server starts in a separate thread for both the web server thread and the main console application.
This is my client:
public static string Communicate(string text)
{
try
{
TcpClient client = new TcpClient(ip, port);
byte[] data = System.Text.Encoding.ASCII.GetBytes(text);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent data: " + text);
data = new Byte[256];
string responseData = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
client.Close();
return responseData;
}
catch (Exception ex)
{
return "An error occured\n" + ex.ToString();
}
}
Problem
I can send one command to the server with a successful return. However, when I try to send another command, the server gives the following error:
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
I know that this is not a problem with the firewall or administrator, as I can successfully send one command. Only when sending the second command does it give this error.
, :

EDIT: , , , , for. , , , :). , , .