gpt4 book ai didi

c# - 使用 Socket 发送对广播的回复

转载 作者:行者123 更新时间:2023-11-30 21:23:37 24 4
gpt4 key购买 nike

我正在尝试发送一个广播,然后让服务器回复它:

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();
}

广播正常到达,但回复没有。不会抛出异常。谁能帮我?我是否必须为回复或其他内容打开一个新连接?

编辑:稍微更改了我的代码,现在可以使用了!感谢您的回复!

最佳答案

您的 SendBroadcast() 套接字似乎没有绑定(bind)到端口,因此他不会收到任何东西。事实上,您的 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() 绑定(bind)到一个不同的端口并更改 ReceiveBroadcast() 发送到那个端口(而不是他自己的端点 ep),或者 (b) 让两个函数使用同一个套接字对象,这样它们就可以在端口 16789 上接收数据报。

关于c# - 使用 Socket 发送对广播的回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1657914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com