2012年5月11日 星期五

about broadcast(C#)

接收:
Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 100);
sock.EnableBroadcast = true;
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
sock.ReceiveTimeout = 1000;
IPEndPoint iep = new IPEndPoint(IPAddress.Any/*IPAddress.Parse("192.168.1.220")*/, 8027);
sock.Bind(iep);

EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive..." + sock.LocalEndPoint.ToString());

while (runTD)
{
Console.WriteLine("Waiting for data..");

try
{
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
//int recv = sock.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
//dosomething
Console.WriteLine(stringData.Trim());
}
catch
{
Console.WriteLine("timeout!!");
}
}
sock.Close();


發送:
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.EnableBroadcast = true;
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);

IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 8028);

string str = tb_send.Text.ToString();
byte[] data = Encoding.ASCII.GetBytes(str);

sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 100);
sock.SendTo(data, iep1);

sock.Close();

注意:若收不到請檢察防火牆。


demo download : https://docs.google.com/open?id=0B2Mp2cW7CWo5bEo5NWp4WGNSZ1U

沒有留言: