正確判斷socket是否處於連接狀態

msdn上說:

The Connected property gets the connection state of the Socket as of the last I/O operation. When it returns false, the Socket was either never connected, or is no longer connected.

The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

所以不能用Socket.Connected判斷。

使用方法:

            private bool SocketConnected()  
            {  
                try  
                {  
                    return !_socket.Poll(1, SelectMode.SelectRead) && (_socket.Available == 0);  
                }  
                catch (SocketException)  
                {  
                    return false;  
                }  
                catch (ObjectDisposedException)  
                {  
                    return false;  
                }  
            }   


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章