我正在尝试发送广播以联系我的应用程序的其他实例。我在 Mac 上的 Mono 3 Console 程序中运行下面的代码(但也在 Windows 上尝试过 VS2012)。但是,从未收到该消息。接收者只是坐在那里并在通话中阻塞
byte[] data = udpClient.Receive (ref endPoint);
编辑:
我试过:
var recipient = new IPEndPoint (new IPAddress(new byte[] {192, 255, 255, 255}), 1667);
并且还添加了
udpClient.EnableBroadcast = true;
给发件人。仍然:没有收到任何东西。就是这样。有什么建议吗?
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace NetworkServiceTest_Console
{
class MainClass
{
public static void Main (string[] args)
{
Task.Run (() => Receiver ());
Task.Run (() => {
while(true)
{
Sender ();
Thread.Sleep(1000);
}
});
Console.ReadLine ();
}
static void Sender()
{
Console.WriteLine ("Sending...");
var recipient = new IPEndPoint (IPAddress.Broadcast, 667);
var udpClient = new UdpClient ();
var data = Encoding.UTF8.GetBytes("Hallo world!");
int bytesSent = udpClient.Send (data, data.Length, recipient);
udpClient.Close ();
Console.WriteLine ("{0} bytes sent", bytesSent);
}
static void Receiver()
{
Console.WriteLine ("Receiving...");
var udpClient = new UdpClient ();
var endPoint = new IPEndPoint(IPAddress.Any, 667);
byte[] data = udpClient.Receive (ref endPoint);
Console.WriteLine ("Received '{0}'.", Encoding.UTF8.GetString (data));
udpClient.Close ();
}
}
}