我進入了UDP,並決定爲練習做一個小聊天。 我遇到了一個問題,我無法弄清楚自己。c#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();
}
}
嘗試使用多播IP 224-239進行廣播。 braodcast IP 255.255.255.255是爲某些協議保留的。我從來沒有能夠得到它的工作。 – jdweng