我正在尝试发送广播,然后让服务器回复它:
public static void SendBroadcast()
{
byte[] buffer = new byte[1024];
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
socket.Connect(new IPEndPoint(IPAddress.Broadcast, 16789));
socket.Send(System.Text.UTF8Encoding.UTF8.GetBytes("Anyone out there?"));
var ep = socket.LocalEndPoint;
socket.Close();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(ep);
socket.Receive(buffer);
var data = UTF8Encoding.UTF8.GetString(buffer);
Console.WriteLine("Got reply: " + data);
socket.Close();
}
public static void ReceiveBroadcast()
{
byte[] buffer = new byte[1024];
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var iep = new IPEndPoint(IPAddress.Any, 16789);
socket.Bind(iep);
var ep = iep as EndPoint;
socket.ReceiveFrom(buffer, ref ep);
var data = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Received broadcast: " + data + " from: " + ep.ToString());
buffer = UTF8Encoding.UTF8.GetBytes("Yeah me!");
socket.SendTo(buffer, ep);
socket.Close();
}
广播收到的很好,但答复却没有。没有异常被抛出。谁能帮我?我是否必须为回复打开新连接?
编辑:改变了我的代码,现在它可以工作了!谢谢你的回复!答案 0 :(得分:4)
看起来你的SendBroadcast()
套接字不是一个端口,所以他不会收到任何东西。事实上,你的ReceiveBroadcast()
套接字正在将回复发回给自己的端口,这样他就会收到自己的回复。
ReceiveBroadcast: binds to port 16789
SendBroadcast: sends to port 16789
ReceiveBroadcast: receives datagram on port 16789
ReceiveBroadcast: sends reply to 16789
ReceiveBroadcast: **would receive own datagram if SendTo follwed by Receive**
您需要(a)将SendBroadcast()
绑定到不同的端口,并将ReceiveBroadcast()
发送到该端口(而不是他自己的端点ep
) ,或(b)让两个函数使用相同的套接字对象,以便它们两者在端口16789上接收数据报。