나는 클라이언트를 수락하기 위해 while(!Disposing)
루프에서 AcceptTcpClient()
을 사용합니다.
클래스 I을 Stop()
이라고 부르고 TcpListener
의 기능을 호출하고 Disposing
을 true로 설정하십시오. 이 같은 :
이 서버 클래스의 단지 작은 발췌입니다
public class Server : IDisposable
{
private TcpListener _tcpListener;
private bool _isDisposing;
public void Start()
{
(new Thread(new ThreadStart(ListenForClients))).Start();
}
private void ListenForClients()
{
this._tcpListener = new TcpListener(System.Net.IPAddress.Any, this.ListenPort);
this._tcpListener.Start();
while (!_isDisposing)
{
//blocks until a client has connected to the server
TcpClient client = this._tcpListener.AcceptTcpClient();
if (client == null) continue;
//create a thread to handle communication with connected client
}
}
public void Dispose()
{
this._isDisposing = true;
this._tcpListener.Stop();
}
}
주 ...
이 방법, 프로그램이 AcceptTcpClient()
기능에서 고정 된 위치를 유지할 수 있습니다 여전히 종료 될 수있다.
그러나 청취 자체는 별도의 Thread (Start() function)
에서도 발생해야합니다.
블로킹 소켓 코드를 생산에 투입해서는 안되는 또 다른 이유는 다음과 같습니다. 비동기 소켓 통신은 100 % 신뢰할 수있는 유일한 방법입니다. –