Export (0) Print
Expand All

UdpClient Class

Provides User Datagram Protocol (UDP) network services.

For a list of all members of this type, see UdpClient Members.

System.Object
   System.Net.Sockets.UdpClient

[Visual Basic]
Public Class UdpClient
   Implements IDisposable
[C#]
public class UdpClient : IDisposable
[C++]
public __gc class UdpClient : public IDisposable
[JScript]
public class UdpClient implements IDisposable

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

The UdpClient class provides simple methods for sending and receiving connectionless UDP datagrams in blocking synchronous mode. Because UDP is a connectionless transport protocol, you do not need to establish a remote host connection prior to sending and receiving data. You do, however, have the option of establishing a default remote host in one of the following two ways:

  • Create an instance of the UdpClient class using the remote host name and port number as parameters.
  • Create an instance of the UdpClient class and then call the Connect method.

You can use any of the send methods provided in the UdpClient to send data to a remote device. Use the Receive method to receive data from remote hosts.

Note   Do not call Send using a host name or IPEndPoint if you have already specified a default remote host. If you do, UdpClient will throw an exception.

UdpClient methods also allow you to send and receive multicasted datagrams. Use The JoinMulticastGroup method to subscribe a UdpClient to a multicast group. Use the DropMulticastGroup method to unsubscribe a UdpClient from a multicast group.

Example

[Visual Basic, C#, C++] The following example establishes a UdpClient connection using the host name www.contoso.com on port 11000. A small string message is sent to two separate remote host machines. The Receive method blocks execution until a message is received. Using the IPEndPoint passed to Receive, the identity of the responding host is revealed.

[Visual Basic] 
' This constructor arbitrarily assigns the local port number.
Dim udpClient As New UdpClient()
Try
   udpClient.Connect("www.contoso.com", 11000)
   
   ' Sends a message to the host to which you have connected.
   Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there?")
   
   udpClient.Send(sendBytes, sendBytes.Length)
   
   ' Sends message to a different host using optional hostname and port parameters.
   Dim udpClientB As New UdpClient()
   udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000)
   
   'Blocks until a message returns on this socket from a remote host.
   Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
   
   ' Blocks until a message returns on this socket from a remote host.
   Dim receiveBytes As [Byte]() = udpClient.Receive(RemoteIpEndPoint)
   Dim returnData As String = Encoding.ASCII.GetString(receiveBytes)
   
   ' Which one of these two hosts responded?
   Console.WriteLine(("This is the message you received " + _
                                 returnData.ToString()))
    Console.WriteLine(("This message was sent from " + _
                                 RemoteIpEndPoint.Address.ToString() + _ 
                                 " on their port number " + _
                                 RemoteIpEndPoint.Port.ToString()))
   udpClient.Close()
   udpClientB.Close()
 
Catch e As Exception
   Console.WriteLine(e.ToString())
End Try
   End Sub 

[C#] 
// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient();
    try{
         udpClient.Connect("www.contoso.com", 11000);

         // Sends a message to the host to which you have connected.
         Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
      
         udpClient.Send(sendBytes, sendBytes.Length);

         // Sends a message to a different host using optional hostname and port parameters.
         UdpClient udpClientB = new UdpClient();
         udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000);

         //IPEndPoint object will allow us to read datagrams sent from any source.
         IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

         // Blocks until a message returns on this socket from a remote host.
         Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); 
         string returnData = Encoding.ASCII.GetString(receiveBytes);
   
         // Uses the IPEndPoint object to determine which of these two hosts responded.
         Console.WriteLine("This is the message you received " +
                                      returnData.ToString());
         Console.WriteLine("This message was sent from " +
                                     RemoteIpEndPoint.Address.ToString() +
                                     " on their port number " +
                                     RemoteIpEndPoint.Port.ToString());

          udpClient.Close();
          udpClientB.Close();
          
          }  
       catch (Exception e ) {
                  Console.WriteLine(e.ToString());
        }

[C++] 
// With this constructor the local port number is arbitrarily assigned.
UdpClient __gc *udpClient = new UdpClient();
try {
    udpClient->Connect(S"host.contoso.com", 11000);

    // Send message to the host to which you have connected.
    Byte sendBytes __gc[] = Encoding::ASCII->GetBytes(S"Is anybody there?");

    udpClient->Send(sendBytes, sendBytes->Length);

    // Send message to a different host using optional hostname and port parameters.
    UdpClient __gc *udpClientB = new UdpClient();
    udpClientB->Send(sendBytes, sendBytes->Length, S"AlternateHostMachineName", 11000);

    //IPEndPoint object will allow us to read datagrams sent from any source.
    IPEndPoint __gc *RemoteIpEndPoint = new IPEndPoint(IPAddress::Any, 0);

    // Block until a message returns on this socket from a remote host.
    Byte receiveBytes __gc[] = udpClient->Receive(&RemoteIpEndPoint); 
    String __gc *returnData = Encoding::ASCII->GetString(receiveBytes);

    // Use the IPEndPoint object to determine which of these two hosts responded.
    Console::WriteLine(String::Concat(S"This is the message you received ", returnData->ToString()));
    Console::WriteLine(String::Concat(S"This message was sent from ", RemoteIpEndPoint->Address->ToString(),
                                      S" on their port number ", __box(RemoteIpEndPoint->Port)->ToString()));

    udpClient->Close();
    udpClientB->Close();

}  
catch (Exception __gc *e ) {
    Console::WriteLine(e->ToString());
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Net.Sockets

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: System (in System.dll)

.NET Framework Security: 

  • SocketPermission To establish an outgoing connection or accept an incoming request.

See Also

UdpClient Members | System.Net.Sockets Namespace | TcpClient | TCP/UDP

Show:
© 2014 Microsoft