客户端通过TCP连接成功将字符串数据发送到服务器。当客户端停止或关闭时,服务器代码将在以下代码的string theString = streamReader.ReadLine();
行中退出,并显示“未处理异常”错误。
我可以使用哪些更改或方法使服务器代码正常退出连接和程序?
static void Listeners()
{
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
Console.WriteLine("Client:"+socketForClient.RemoteEndPoint+" now connected to server.");
NetworkStream networkStream = new NetworkStream(socketForClient);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream);
while (true)
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
break;
}
streamReader.Close();
networkStream.Close();
streamWriter.Close();
}
socketForClient.Close();
Console.WriteLine("Press any key to exit from server program");
Console.ReadKey();
}
答案 0 :(得分:1)
赞:
try {
while (true)
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
}
} catch (Exception ex) {
Console.WriteLine("Error: " + ex.Message);
}
就像其他人提到的那样,您应该使用using
语句来帮助您处理一次性用品:
static void Listeners()
{
using (Socket socketForClient = tcpListener.AcceptSocket())
{
if (socketForClient.Connected)
{
Console.WriteLine("Client:" + socketForClient.RemoteEndPoint + " now connected to server.");
using (NetworkStream networkStream = new NetworkStream(socketForClient))
using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream))
using (System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream))
{
try
{
while (true)
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
Console.WriteLine("Press any key to exit from server program");
Console.ReadKey();
}