2010-07-22 2 views
3

나는 TcpListener를 사용하는 스레드를 만들고 내 응용 프로그램이 닫힐 때 thead가 종료되도록하고 싶습니다. 중단을 호출 할 수 있지만 TcpListener가 AcceptTcpClient로 블로킹 중이기 때문에 스레드가 여전히 살아 있습니다.TcpListener 제한 시간/about/something? ASync가 없으면?

AcceptTcpClient를 사용하여 시간 초과 또는 무언가를 설정하거나 할 수 있습니까? 나는 그것이 영원히 막히는 것을 멈추게하는 방법이 없다면 그것이 얼마나 유용 할 지 상상할 수 없다. 내 코드는 직렬이며 그 방법을 유지하고 싶습니다 그래서 BeginAcceptTcpClient를 사용하지 않고 솔루션이 있습니까? ASync 코드를 작성하고 있습니까?

+1

블로킹 소켓 코드를 생산에 투입해서는 안되는 또 다른 이유는 다음과 같습니다. 비동기 소켓 통신은 100 % 신뢰할 수있는 유일한 방법입니다. –

답변

10

간단한 해결책. 대기중인 상태로 확인하십시오.

3

AcceptTcpClient에 대한 호출을 Socket.Select()에 대한 호출로 대체 할 수 있습니다.이 호출은 시간 초과 될 수 있습니다.

var sockl = new ArrayList { listener.Server }; 
Socket.Select(sockl, null, null, _timeout_); 
if (sockl.Contains(listener.Server)) listener.AcceptTcpClient(); 
3

나는 클라이언트를 수락하기 위해 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)에서도 발생해야합니다.

관련 문제