gpt4 book ai didi

c# - C#udp广播包未收到

转载 作者:行者123 更新时间:2023-12-03 12:03:58 24 4
gpt4 key购买 nike

我进入UDP并决定进行一次小型聊天,仅供练习。
我遇到了一个问题,我自己也无法解决。

我创建了两个完全相同的C#控制台程序(只是端口不同)

我发送了UDP广播程序包,然后希望在第二个控制台程序上接收它。发生的情况是,我发送广播的程序接收了该广播,而其他程序没有。反之亦然。

我已经关闭了防火墙->不会进行任何更改。

我将整个代码发布给您,希望你们能为我提供帮助,我真的很乐意继续前进!太感谢了!

class Program
{
const int PORT = 10101;
private static readonly UdpClient udpclient = new UdpClient(PORT);
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
udpclient.EnableBroadcast = true;
//bool for calling async receiver just once
bool receiving = false;
Console.WriteLine("Chat 2");
//to keep while loop running --> change later
bool keepchatting = true;
#region keepchating loop
while (keepchatting)
{
if (!receiving)
{
startlistening();
}
receiving = true;
newmessage();
}
}
#endregion

//new message --> call sendmessage to broadcast text via UDP
public static void newmessage()
{
string msg;
msg = Console.ReadLine();
byte[] message = Encoding.ASCII.GetBytes(msg);
sendmessage(message);
}

//Broadcast text via UDP
public static void sendmessage(byte[] tosend)
{
UdpClient client = new UdpClient();
client.EnableBroadcast = true;
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT);
client.Send(tosend, tosend.Length, ip);
client.Close();
Console.WriteLine("Sent!");
}

static IAsyncResult ar = null;
//Setup Async Receive Method
public static void startlistening()
{
ar = udpclient.BeginReceive(RecievedMessage, new object());
}

//Message
public static void RecievedMessage(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT);
byte[] bytes = udpclient.EndReceive(ar, ref ip);
string msg = Encoding.ASCII.GetString(bytes);
Console.WriteLine("Received: " + msg);
startlistening();
}

}

最佳答案

我只更改了您的代码的两部分,在每个客户端上设置另一个客户端的远程端口号,请尝试以下操作:

在一个客户端上:

const int PORT = 10101;
const int PORT_Remote = 10102;

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_Remote);

在另一个客户端上:
const int PORT = 10102;
const int PORT_Remote = 10101;

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_Remote);

关于c# - C#udp广播包未收到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41619269/

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