我希望每个客户端都能“了解”应要求在UDP网络中连接的所有其他客户端。
到目前为止,我有一个非常简单的程序,其中每个客户端都输入一个用户名并将其发送到网络。每个客户端都存储一个用户名列表,以跟踪谁与网络进行了至少一次通信。如果弹出新用户名,则会将其输出到控制台,并将其存储在列表中,以防止再次输出。
这一切都很好,但我只能通过让每个客户端不断等待来自网络的新数据来管理上述情况(因为它永远无法知道新客户端何时会停止“进入”网络)。
这是所有代码。感兴趣的部分可能是displayAllUsers()函数。
我粘贴了整个程序,因为(i)很短(ii)我在C#中对UDP的了解非常绿色,而且我的做法也绝非好事,因此拥有读者也许是一个好主意意识到这一点。
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Node
{
class Program
{
static UdpClient client = new UdpClient();
static IPEndPoint localIP;
static IPEndPoint remoteIP;
static String currentUser;
static List<String> currentUsers = new List<String>();
static void Main(string[] args)
{
initialiseListener();
initialiseWriter();
Console.WriteLine("What's your username?");
currentUser = Console.ReadLine();
Byte[] buffer = Encoding.Unicode.GetBytes(currentUser);
//Who is current user?
client.Send(buffer, buffer.Length, remoteIP);
Console.WriteLine("Here are all active users:");
displayAllUsers();
}
private static void displayAllUsers()
{
Byte[] buffer;
while (true)
{
Byte[] data = client.Receive(ref localIP); //blocking call - continuously listening
string strData = Encoding.Unicode.GetString(data);
if (!currentUsers.Contains(strData)) //if data is not found in current users list...
{
Console.WriteLine(strData); //write username on screen
currentUsers.Add(strData); //and add to current users list
buffer = Encoding.Unicode.GetBytes(currentUser); //Convert currentUser to bytes
client.Send(buffer, buffer.Length, remoteIP); //and send new current user to everyone else
}
}
}
private static void initialiseWriter()
{
IPAddress multicastAddress = IPAddress.Parse("239.0.0.222");
client.JoinMulticastGroup(multicastAddress);
//Send data to this multicast address group
remoteIP = new IPEndPoint(multicastAddress, 2222); //To write to the multicastAddress group on port 2222
}
private static void initialiseListener()
{
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.ExclusiveAddressUse = false;
//More than one client can use the port to be specified
localIP = new IPEndPoint(IPAddress.Any, 2222); //To listen on any IP Address available from the port 2222
client.Client.Bind(localIP); //Associate client with listener
}
}
}
理想情况下,每个客户端将能够随时请求displayAllUsers()设备并为其生成此类列表,而不必一直等待新的客户端加入。
最终,我想将我的UDP和非集中式网络知识应用到Xamarin应用程序中,并让每台设备都知道其他所有打开了该应用程序的设备。
答案 0 :(得分:0)
我从here找到了解决方案,并在displayAllUsers()方法中修改了以下内容。
if(client.Available > 0){
data = client.Receive(ref localIP); //blocking call - continuously listening
}else{
break;
}
使用.Available属性非常有用,因为它可以检查是否有需要听的东西-正是我需要的东西。
如果发现是好的做法,我会将其标记为线程的答案。