[第一次发帖][讨论][求教][散分][高分]MSDN中C#的Udp示例中的疑惑
vs.net2003
示例
[Visual Basic, C#, C++] 下面的示例将无连接数据文报发送到指定的远程主机。偏移量、大小和 SocketFlags 将被传递给 SendTo 方法。
[Visual Basic, C#, C++] 注意 此示例显示如何使用 SendTo 的一个重载版本。有关其他可用示例,请参阅单独的重载主题。
[C#]
IPHostEntry lipa = Dns.Resolve( "host.contoso.com ");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);
Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
byte[] msg = Encoding.ASCII.GetBytes( "This is a test ");
try{
// Sends datagram to the IpEndPoint specified. This call blocks.
s.SendTo(msg, 0, msg.Length, SocketFlags.None, lep);
// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
// Creates a byte buffer to receive the message.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer, 0, 100, SocketFlags.None, ref tempRemoteEP);
// Displays the information received to the screen.
Console.WriteLine( " I received the following message : " +
Encoding.ASCII.GetString(buffer));
}
catch(Exception e){
Console.WriteLine( "Exception : " + e.ToString());
}
或者UdpClient的例子
示例
[Visual Basic, C#] 下面的示例使用主机名 www.contoso.com 在端口