المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : c# socket server error



C# Programming
05-05-2009, 05:22 PM
Hi,

I have this problem with C# socket server that's talking to a perl client. When I run the server and run the perl client with "perl client.pl commandtoexecute" the server executes the command displaying it on the server console and then crashes with this error:

Unhandled Exception: System.IO.IOException: Unable to read data from the transpo
rt connection: An existing connection was forcibly closed by the remote host. --
-> System.Net.Sockets.SocketException: An existing connection was forcibly close
d 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 s
ize)
--- End of inner exception stack trace ---

I know I am not handling the error correctly, but I have no idea how do I go about fixing this. Any ideas? here is the code for the method that is handling the client connections:

public void HandleConnection()
{
int recv;
byte[] data = new byte[2048000];

TcpClient client = threadListener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
connections++;
Console.WriteLine("New client accepted: {0} active connections", connections);
string welcome = "Welcome to power shell server ... ";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
while (true)
{
data = new byte[2048000];
recv = ns.Read(data, 0, data.Length);
if (recv == 0)
break;
else
{
String cmd = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(cmd);
//Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
//ns.Write(Encoding.UTF8.GetBytes(RunShell(cmd)), Convert.ToString((RunShell(cmd))).Length, 10000000);

// Execute incoming shell command and convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(RunShell(cmd));

// Begin sending the data to the remote device.
if (byteData.Length > 0)
ns.Write(byteData, 0, byteData.Length);
else
{
Console.Write("\nData Length is less than 0");
ns.Write(data, 0, recv);
}
}
}
ns.Close();
client.Close();
connections--;
Console.WriteLine("Client disconnected: {0} active connections", connections);
}