我正在尝试发送广播以联系我的应用程序的其他实例。我正在Mac上的Mono 3控制台程序中运行下面的代码(但在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 ();
}
}
}
答案 0 :(得分:3)
这应该可以解决问题:
static void Receiver( )
{
Console.WriteLine( "Receiving..." );
var udpClient = new UdpClient( 667 );
var endPoint = new IPEndPoint( IPAddress.Any, 0 );
byte[] data = udpClient.Receive( ref endPoint );
Console.WriteLine( "Received '{0}'.", Encoding.UTF8.GetString( data ) );
udpClient.Close( );
}
在UdpClient构造函数中提供端口号,而不是在Receive()方法中。接收的端点似乎像out参数一样使用,而不是输入参数。
答案 1 :(得分:1)
我在那里看到两个可能的问题:
UdpClient.EnableBroadcast
设置为true
。请参阅msdn。如果仍然无效,请使用网络嗅探器(例如wireshark)来分析流量。