Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

c# - How to broadcast a UDP packet on WP7 Mango?

I want to send a UDP packet from a phone to the limited broadcast address (IPAddress.Broadcast = 255.255.255.255).

This is what I have so far, and it works in a Windows app:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);   
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);   

byte[] data = Encoding.UTF8.GetBytes("test data");   

SocketAsyncEventArgs a = new SocketAsyncEventArgs();   

a.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 11000);   
a.SetBuffer(data, 0, data.Length);   

a.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
  Console.WriteLine(e.SocketError);
});

socket.SendToAsync(a);   

The SetSocketOption call is required in order to prevent an "access denied" exception. Unfortunately that method doesn't seem to be available on WP7. The UDP sample code given on the App Hub community site is using multicast to achieve similar results, but the device I'm trying to contact isn't able to deal with multicast.

Is there any way to do this sort of broadcast on Mango?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use socket.ConnectAsync(a);.

From Documentation:

Optionally, a buffer may be provided which will atomically be sent on the socket after the ConnectAsync method succeeds. (UDP is a connectionless protocol, should send always when network works)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...