.NET 简单实现广播
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program
{
static bool connecting = true;
static void Main()
{
Received();
while (connecting)
{
string content = Console.ReadLine();
if (content.Length > 0)
{
if (string.Compare(content, "<Stop>", true) == 0)
{
Console.WriteLine("关闭...");
connecting = false;
}
else
{
Send(content);
}
}
}
Console.ReadKey();
}
public static void Send(string content)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);//255.255.255.255
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.100.255"), 9050);
// string hostname = Dns.GetHostName();
byte[] data = Encoding.ASCII.GetBytes(content);
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
//sock.SendTo(data, iep1);
sock.SendTo(data, iep2);
sock.Close();
}
public static void Received()
{
ThreadPool.QueueUserWorkItem((x) =>
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
byte[] data;
int recv;
string stringData;
Console.WriteLine("接听开启...");
while (connecting)
{
data = new byte[1024];
recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("信息: {0} 来自: {1}", stringData, ep.ToString());
}
Console.WriteLine("接听关闭...");
sock.Close();
});
}
}
{
static bool connecting = true;
static void Main()
{
Received();
while (connecting)
{
string content = Console.ReadLine();
if (content.Length > 0)
{
if (string.Compare(content, "<Stop>", true) == 0)
{
Console.WriteLine("关闭...");
connecting = false;
}
else
{
Send(content);
}
}
}
Console.ReadKey();
}
public static void Send(string content)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);//255.255.255.255
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.100.255"), 9050);
// string hostname = Dns.GetHostName();
byte[] data = Encoding.ASCII.GetBytes(content);
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
//sock.SendTo(data, iep1);
sock.SendTo(data, iep2);
sock.Close();
}
public static void Received()
{
ThreadPool.QueueUserWorkItem((x) =>
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
byte[] data;
int recv;
string stringData;
Console.WriteLine("接听开启...");
while (connecting)
{
data = new byte[1024];
recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("信息: {0} 来自: {1}", stringData, ep.ToString());
}
Console.WriteLine("接听关闭...");
sock.Close();
});
}
}