您的位置:首页 > 其它

UdpClient类使用

2016-05-17 16:24 232 查看
UdpCLient类使用

构造函数

方法

通信流程

实例

UdpCLient类使用

说明: 本文摘录自MSDN UdpClient类

有删减,将常使用的方法列出

构造函数

名称说明
UdpClient()初始化 UdpClient 类的新实例
UdpClient(Int32)新实例初始化 UdpClient 类,并将其绑定到提供的本地端口号。
UdpClient(IPEndPoint)初始化 UdpClient 类的新实例,并将其绑定到指定的本地终结点。
UdpClient(String, Int32)新实例初始化 UdpClient 类,并建立默认远程主机。

方法

名称说明
Connect(IPAddress, Int32)建立默认远程主机使用指定的 IP 地址和端口号。
Connect(IPEndPoint)建立默认远程主机使用指定的网络终结点。
Connect(String, Int32)建立默认远程主机使用指定主机名和端口号。
Close()关闭 UDP 连接。
Send(Byte[], Int32)将 UDP 数据报发送到远程主机。

通信流程

Created with Raphaël 2.1.0开始实例化UdpClient,可绑定到本地端口获取目标IP地址和端口Connect()Send()Close() 结束

实例

UdpClient udpClient = new UdpClient(11000);
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());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: