[C#]實作UDP Broadcast的傳送與接收
private static void BroadcastMessage(byte[] message, int port)
{
using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp))
{
sock.EnableBroadcast = true;
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
var iep = new IPEndPoint(IPAddress.Broadcast, port);
sock.SendTo(message, iep);
}
}</pre></div>
private void ReceiveBroadcastMessage(Action<EndPoint, byte[]> receivedAction, int port)
{
using (var sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp)) { var ep = new IPEndPoint(IPAddress.Any, port) as EndPoint; sock.Bind(ep);
while (true)
{
var buffer = new byte[1024];
var recv = sock.ReceiveFrom(buffer, ref ep);
var data = new byte[recv];
Array.Copy(buffer, 0, data, 0, recv);
receivedAction(ep, data);
Thread.Sleep(500);
Application.DoEvents();
}
}
}</pre></div>
namespace WindowsFormsApplication8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{
BroadcastMessage("This is a test message", 9051);
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ReceiveBroadcastMessage((EndPoint ep, string data) =>
{
this.Invoke((MethodInvoker)delegate()
{
listBox1.Items.Add(string.Format("received: {0} from: {1}",
data, ep.ToString()));
});
}, 9051);
}
private static void BroadcastMessage(string message, int port)
{
BroadcastMessage(Encoding.ASCII.GetBytes(message), port);
}
private static void BroadcastMessage(byte[] message, int port)
{
using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp))
{
sock.EnableBroadcast = true;
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
var iep = new IPEndPoint(IPAddress.Broadcast, port);
sock.SendTo(message, iep);
}
}
private void ReceiveBroadcastMessage(Action<EndPoint, string> receivedAction, int port)
{
ReceiveBroadcastMessage((ep, data) =>
{
var stringData = Encoding.ASCII.GetString(data);
receivedAction(ep, stringData);
}, port);
}
private void ReceiveBroadcastMessage(Action<EndPoint, byte[]> receivedAction, int port)
{
using (var sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp)) { var ep = new IPEndPoint(IPAddress.Any, port) as EndPoint; sock.Bind(ep);
while (true)
{
var buffer = new byte[1024];
var recv = sock.ReceiveFrom(buffer, ref ep);
var data = new byte[recv];
Array.Copy(buffer, 0, data, 0, recv);
receivedAction(ep, data);
Thread.Sleep(500);
Application.DoEvents();
}
}
}
}
}