我一直在制作一个示例程序,用户可以使用套接字和 UDP 连接来广播消息。它在局域网上取得了成功,但我不能将我的消息广播到其他网络(例如10.15.1.11的消息到10.11.1.23)。这是我的示例代码:
监听器:
bworker =发件人为BackgroundWorker;
Socket _ListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint _ListenerEndPoint = new IPEndPoint(IPAddress.Any, _port);
_ListenerSocket.EnableBroadcast = true;
_ListenerSocket.Bind(_ListenerEndPoint);
//_ListenerSocket.Connect(MulticastIP, _port);
_ListenerSocket.Ttl = 255;
_ListenerSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(MulticastIP));
while (true)
{
byte[] msg = new byte[1024];
_ListenerSocket.Receive(msg);
string StringData = Encoding.Unicode.GetString(msg);
bworker.ReportProgress(0, StringData);
}
发件人:
Socket _ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_ClientSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(MulticastIP));
_ClientSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, int.Parse(ttl));
IPEndPoint _ClientEndPoint = new IPEndPoint(MulticastIP, _port);
_ClientSocket.Connect(_ClientEndPoint);
byte[] MsgByte = new byte[1024];
MsgByte = Encoding.Unicode.GetBytes(txtmsg.Text);
_ClientSocket.Send(MsgByte);
变量:
public const int _port = 8041;
public const string ttl = "255";
public IPAddress MulticastIP = IPAddress.Parse("239.0.0.222");
感谢。