Socket.Connected 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
public:
property bool Connected { bool get(); };
public bool Connected { get; }
member this.Connected : bool
Public ReadOnly Property Connected As Boolean
屬性值
如果最近一次的作業是將 Socket 連接到遠端資源,則為 true
,否則,即為 false
。
範例
下列程式代碼範例會連線到遠端端點、檢查 Connected 屬性,以及檢查連線的目前狀態。
client->Connect( anEndPoint );
if ( !client->Connected )
{
Console::WriteLine( "Winsock error: {0}", Convert::ToString(
System::Runtime::InteropServices::Marshal::GetLastWin32Error() ) );
}
// This is how you can determine whether a socket is still connected.
bool blockingState = client->Blocking;
try
{
array<Byte>^tmp = gcnew array<Byte>(1);
client->Blocking = false;
client->Send( tmp, 0, static_cast<SocketFlags>(0) );
Console::WriteLine( L"Connected!" );
}
catch ( SocketException^ e )
{
// 10035 == WSAEWOULDBLOCK
if ( e->NativeErrorCode.Equals( 10035 ) )
{
Console::WriteLine( "Connected from an exception!" );
}
else
{
Console::WriteLine( "Disconnected: {0}!", e->NativeErrorCode );
}
}
finally
{
client->Blocking = blockingState;
}
Console::WriteLine( "Connected: {0}", client->Connected );
// .Connect throws an exception if unsuccessful
client.Connect(anEndPoint);
// This is how you can determine whether a socket is still connected.
bool blockingState = client.Blocking;
try
{
byte [] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0);
Console.WriteLine("Connected!");
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
Console.WriteLine("Still Connected, but the Send would block");
}
else
{
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
}
}
finally
{
client.Blocking = blockingState;
}
Console.WriteLine("Connected: {0}", client.Connected);
' .Connect throws an exception if unsuccessful
client.Connect(anEndPoint)
' This is how you can determine whether a socket is still connected.
Dim blockingState As Boolean = client.Blocking
Try
Dim tmp(0) As Byte
client.Blocking = False
client.Send(tmp, 0, 0)
Console.WriteLine("Connected!")
Catch e As SocketException
' 10035 == WSAEWOULDBLOCK
If e.NativeErrorCode.Equals(10035) Then
Console.WriteLine("Still Connected, but the Send would block")
Else
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode)
End If
Finally
client.Blocking = blockingState
End Try
Console.WriteLine("Connected: {0}", client.Connected)
End Sub
備註
屬性 Connected
會從最後一個 I/O 作業開始取得 的連接 Socket 狀態。 當傳回 false
時, Socket 表示從未連接,或已不再連接。
Connected
不是安全線程;當 與另一個線程中斷連線時Socket,可能會在中止作業之後傳回 true
。
屬性的值 Connected 會反映連線狀態,如同最近一次的作業一樣。 如果您需要判斷連線的目前狀態,請建立非封鎖、零位元組的 Send 呼叫。 如果呼叫成功傳回或擲回 WAEWOULDBLOCK 錯誤碼, (10035) ,則套接字仍已連線;否則,套接字已不再連線。
如果您在 UDP) 套接字 (使用者數據報通訊協定上呼叫 Connect ,屬性 Connected 一律會傳回 true
;不過,此動作不會變更 UDP 固有的無連線本質。