2011-04-18 88 views

回答

5

創建cusomt插座類繼承.NET套接字類:

public delegate void SocketEventHandler(Socket socket); 
    public class CustomSocket : Socket 
    { 
     private readonly Timer timer; 
     private const int INTERVAL = 1000; 

     public CustomSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) 
      : base(addressFamily, socketType, protocolType) 
     { 
      timer = new Timer { Interval = INTERVAL }; 
      timer.Tick += TimerTick; 
     } 

     public CustomSocket(SocketInformation socketInformation) 
      : base(socketInformation) 
     { 
      timer = new Timer { Interval = INTERVAL }; 
      timer.Tick += TimerTick; 
     } 

     private readonly List<SocketEventHandler> onCloseHandlers = new List<SocketEventHandler>(); 
     public event SocketEventHandler SocketClosed 
     { 
      add { onCloseHandlers.Add(value); } 
      remove { onCloseHandlers.Remove(value); } 
     } 

     public bool EventsEnabled 
     { 
      set 
      { 
       if(value) 
        timer.Start(); 
       else 
        timer.Stop(); 
      } 
     } 

     private void TimerTick(object sender, EventArgs e) 
     { 
      if (!Connected) 
      { 
       foreach (var socketEventHandler in onCloseHandlers) 
        socketEventHandler.Invoke(this); 
       EventsEnabled = false; 
      } 
     } 

     // Hiding base connected property 
     public new bool Connected 
     { 
      get 
      { 
       bool part1 = Poll(1000, SelectMode.SelectRead); 
       bool part2 = (Available == 0); 
       if (part1 & part2) 
       return false; 
       else 
       return true; 
      } 
     } 
    } 

然後使用它是這樣的:

 var socket = new CustomSocket(
       //parameters 
       ); 

     socket.SocketClosed += socket_SocketClosed; 
     socket.EventsEnabled = true; 


     void socket_SocketClosed(Socket socket) 
     { 
      // do what you want 
     } 

我剛剛實施了每個插座套接字關閉事件。所以你的應用程序應該爲這個事件註冊事件處理程序。那麼套接字會通知你的應用程序,如果它本身是關閉的;)

如果代碼有問題,通知我。

+0

Socket.Connected不可實現 – Will 2011-04-18 04:48:33

+0

在自定義類中實現的新的關聯屬性。嘗試一下,它會奏效。 – 2011-04-18 04:53:02

+0

Poll方法在linux上不起作用。即使套接字已關閉,它仍會繼續返回false。這就是爲什麼我正在尋找一種不使用投票的方式。 – Will 2011-04-18 05:01:09

0

Socket類有一個Connected屬性。根據MSDN,檢查呼叫是非阻塞的。這不是你想要的嗎?

+0

這是輪詢解決方案 – 2011-04-18 04:38:26

+0

連接屬性似乎總是​​如此,除非我自己斷開套接字。我只是檢查,即使套接字被遠程服務器斷開,它仍然返回true。 – Will 2011-04-18 04:39:22