我有一個聊天室應用程式,它有服務器和客戶端兩部分。
服務器部分可以接收來自多個客戶端的資料。到目前為止,一切都很好。
但是當其中一個客戶離開時,軟體會出錯!
這是服務器源代碼:
我評論了軟體出錯的那一行!!!
Socket _server;
private void StartServer()
{
_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100010));
_server.Listen(1);
while (true) {
Socket client = _server.Accept();
Thread rd = new Thread(ReceiveData);
rd.Start(client);
}
}
public void ReceiveData(object skt)
{
Socket socket = (Socket)skt;
while (true) {
byte[] buffer = new byte[1024];
int r = socket.Receive(buffer);// when a client leave here get an error !!!
if (r > 0)
Console.WriteLine(socket.RemoteEndPoint.Address ": " Encoding.Unicode.GetString(b));
}
}
錯誤:
An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
Additional information: An existing connection was forcibly closed by the remote host
我該如何解決?
uj5u.com熱心網友回復:
您應該只處理例外:
try
{
// code that uses the socket
}
catch (SocketException e) when (e.SocketErrorCode is SocketError.ConnectionAborted)
{
// code to handle the situation gracefully
}
或者,如果您使用的是較舊的編譯器:
try
{
// code that uses the socket
}
catch (SocketException e)
{
if(e.SocketErrorCode != SocketError.ConnectionAborted)
{
// rethrow the exception
throw;
}
// code to handle the situation gracefully
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447342.html
