次の方法で共有


Socket.EndReceiveFrom メソッド

特定のエンドポイントからの、保留中の非同期読み込みを終了します。

Public Function EndReceiveFrom( _
   ByVal asyncResult As IAsyncResult, _   ByRef endPoint As EndPoint _) As Integer
[C#]
public int EndReceiveFrom(IAsyncResultasyncResult,   ref EndPointendPoint);
[C++]
public: int EndReceiveFrom(IAsyncResult* asyncResult,   EndPoint** endPoint);
[JScript]
public function EndReceiveFrom(
   asyncResult : IAsyncResult,endPoint : EndPoint) : int;

パラメータ

  • asyncResult
    この非同期操作の状態情報およびユーザー定義データを格納する IAsyncResult
  • endPoint
    ソース EndPoint

戻り値

正常に完了した場合は、受信したバイト数。失敗した場合は、0 を返します。

例外

例外の種類 条件
ArgumentNullException asyncResult が null 参照 (Visual Basic では Nothing) です。
ArgumentException BeginReceiveFrom メソッドへの呼び出しで asyncResult が返されませんでした。
InvalidOperationException EndReceiveFrom が、非同期の読み取りのために以前に呼び出されています。
SocketException ソケットへのアクセスを試みているときにエラーが発生しました。詳細については「解説」を参照してください。
ObjectDisposedException Socket は閉じられています。

解説

EndReceiveFrom メソッドは、 BeginReceiveFrom メソッドで開始された非同期の読み取り操作を完了します。

BeginReceiveFrom を呼び出す前に、 AsyncCallback デリゲートを実装するコールバック メソッドを作成する必要があります。このコールバック メソッドは個別のスレッドで実行され、 BeginReceiveFrom の終了時に呼び出されます。コールバック メソッドは、 BeginReceiveFrom メソッドからパラメータとして返された IAsyncResult を受け取る必要があります。

コールバック メソッド内では、 IAsyncResultAsyncState メソッドを呼び出して、 BeginReceiveFrom メソッドに渡された状態オブジェクトを取得します。この状態オブジェクトから受信した Socket を抽出してください。 Socket を取得したら、 EndReceiveFrom メソッドを呼び出して読み取り操作を正常に完了し、読み取られたバイト数を返すことができます。

EndReceiveFrom メソッドは、データが使用可能になるまでブロックします。コネクションレスのプロトコルを使用している場合、 EndReceiveFrom は、受信ネットワーク バッファ内で使用できる、最初にキューに格納されたデータグラムを読み取ります。コネクション指向のプロトコルを使用している場合、 EndReceiveFrom メソッドは、 BeginReceiveFrom メソッドの size パラメータで指定したバイト数までの、使用可能なデータをすべて読み取ります。リモート ホストが Shutdown メソッドで Socket 接続をシャットダウンし、使用できるデータがすべて受信されると、 EndReceiveFrom メソッドはすぐに完了して、0 バイトを返します。受信したデータを取得するには、 IAsyncResult オブジェクトの AsyncState メソッドを呼び出して、結果として得られる状態オブジェクト内のバッファを抽出します。送信元ホストを確認するには、 EndPoint を抽出して IPEndPoint にキャストします。 IPEndPoint.Address メソッドを使用すると IP アドレスを取得できます。 IPEndPoint.Port メソッドはポート番号を取得するときに使用します。

メモ    SocketException が発生した場合は、 SocketException.ErrorCode を使用して具体的なエラー コードを取得してください。このコードを取得したら、Windows Socket Version 2 API エラー コードのマニュアルから、エラーの詳細情報を確認できます。これは MSDN から入手できます。

使用例

[Visual Basic, C#, C++] 特定の EndPoint からの保留中の非同期読み取りを終了する例を次に示します。

 
Dim so As StateObject = CType(ar.AsyncState, StateObject)
Dim s As Socket = so.workSocket

' Creates a temporary EndPoint to pass to EndReceiveFrom.
Dim sender As New IPEndPoint(IPAddress.Any, 0)
Dim tempRemoteEP As EndPoint = CType(sender, EndPoint)

Dim read As Integer = s.EndReceiveFrom(ar, tempRemoteEP)


If read > 0 Then
   so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read))
   s.BeginReceiveFrom(so.buffer, 0, StateObject.BUFFER_SIZE, 0, tempRemoteEP, New AsyncCallback(AddressOf Async_Send_Receive.ReceiveFrom_Callback), so)
Else
   If so.sb.Length > 1 Then
      'All the data has been read, so displays it to the console.
      Dim strContent As String
      strContent = so.sb.ToString()
      Console.WriteLine([String].Format("Read {0} byte from socket" + "data = {1} ", strContent.Length, strContent))
   End If
   s.Close()
End If 
   End Sub 'ReceiveFrom_Callback
   

[C#] 
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket;

   // Creates a temporary EndPoint to pass to EndReceiveFrom.
   IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;

   int read = s.EndReceiveFrom(ar, ref tempRemoteEP); 


if (read > 0) {
        so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
        s.BeginReceiveFrom(so.buffer, 0, StateObject.BUFFER_SIZE, 0, ref tempRemoteEP,
                                 new AsyncCallback(Async_Send_Receive.ReceiveFrom_Callback), so);
}
else{
     if (so.sb.Length > 1) {
          //All the data has been read, so displays it to the console.
          string strContent;
          strContent = so.sb.ToString();
          Console.WriteLine(String.Format("Read {0} byte from socket" + 
                             "data = {1} ", strContent.Length, strContent));
     }
     s.Close();
     
}

[C++] 
StateObject* so = __try_cast<StateObject*>(ar->AsyncState);
Socket* s = so->workSocket;

// Creates a temporary EndPoint to pass to EndReceiveFrom.
IPEndPoint* sender = new IPEndPoint(IPAddress::Any, 0);
EndPoint* tempRemoteEP = __try_cast<EndPoint*>(sender);

int read = s->EndReceiveFrom(ar, &tempRemoteEP); 

if (read > 0) {
    so->sb->Append(Encoding::ASCII->GetString(so->buffer, 0, read));
    s->BeginReceiveFrom(so->buffer, 0, StateObject::BUFFER_SIZE, SocketFlags::None, &tempRemoteEP,
        new AsyncCallback(0, &Async_Send_Receive::ReceiveFrom_Callback), so);
} else {
    if (so->sb->Length > 1) {
        //All the data has been read, so displays it to the console.
        String* strContent = so->sb->ToString();
        Console::WriteLine(S"Read {0} byte from socket data = {1}",
            __box(strContent->Length), strContent);
    }
    s->Close();
}

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET, Common Language Infrastructure (CLI) Standard

参照

Socket クラス | Socket メンバ | System.Net.Sockets 名前空間 | 非同期呼び出しの組み込み