我正在研究 C# 中的广播信标,它应该向所有监听设备广播服务器信息。发送的信息将包含诸如 WCF 服务的 URL、命名空间、所需参数列表等信息。我现在拥有的是一个发送者和接收者,当它们在同一台计算机上时,它们可以完美地交谈。但是,一旦我将发送者放在接收者之外的另一台计算机上,发送者会发送它的消息,但我的接收者永远不会收到它。没有抛出异常,并且两台机器上的防火墙都被禁用。
http://codeidol.com/csharp/csharp-network/IP-Multicasting/What-Is-Broadcasting/是我从中获取代码的地方。
发件人:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UDPTest
{
class Program
{
static void Main(string[] args)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9050);
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
sock.SendTo(data, iep);
sock.Close();
}
}
}
接收者:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UDPBroadcastReciever
{
class Program
{
static void Main(string[] args)
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to recieve");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Received: {0} from: {1}", stringData, ep.ToString());
sock.Close();
Console.ReadLine();
}
}
}
有谁知道我遗漏的任何东西可以使这两个人在两台不同的计算机上交谈?它们位于同一子网 (192.168.1.x)
谢谢尼克朗