[英]List of clients connected to Udp Server in C#
我有一個適用於Udp的套接字程序。
我想管理連接到服務器的客戶端。
例如,如果客戶端連接到服務器,則將該客戶端添加到列表中。 我已經使用以下代碼在Tcp 中完成了此操作:
static readonly Dictionary <int, TcpClient> list_clients = new Dictionary <int, TcpClient>();
例如,只有在列表中的客戶,他的消息才會被寫入。
我將每個客戶端與GetStream()
。 但是在 Udp 中我不知道該怎么做。 我可以管理客戶嗎?
編輯
我使用以下代碼從客戶端接收消息:
private static UdpClient udpServer = new UdpClient(11000);
private static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 11000);
static void Main(string[] args)
{
var firstData = udpServer.Receive(ref remoteEP);
Console.WriteLine(Encoding.ASCII.GetString(firtsData);
}
提前致謝
這段代碼很適合我!
服務器:
public partial class Server : Form
{
public Server()
{
InitializeComponent();
}
void Print(string message)
{
listBox1.Items.Add(message);
}
private void button1_Click(object sender, EventArgs e)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Loopback, 55555));
byte[] vs = new byte[100];
EndPoint senderRemote = new IPEndPoint(IPAddress.Any, 0);
Dictionary<EndPoint, int> pairs = new Dictionary<EndPoint, int>();
int id = 0;
for (int ii = 0; ii < 5; ii++)
{
socket.ReceiveFrom(vs, ref senderRemote);
if (pairs.ContainsKey(senderRemote))
Print(pairs[senderRemote].ToString() + " says:");
else
{
pairs.Add(senderRemote, id++);
Print("new sender");
}
Print(senderRemote.ToString());
Print(Encoding.Unicode.GetString(vs));
socket.SendTo(vs, senderRemote);
}
}
}
客戶:
public partial class Client : Form
{
public Client()
{
InitializeComponent();
}
Socket socket;
private void button1_Click(object sender, EventArgs e)
{
socket.Send(Encoding.Unicode.GetBytes("Gholamam!"));
byte[] vs = new byte[100];
socket.Receive(vs);
listBox1.Items.Add(Encoding.Unicode.GetString(vs));
}
private void Client_Load(object sender, EventArgs e)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Loopback, new Random().Next(1024,65000)));
socket.Connect(IPAddress.Loopback, 55555);
}
}
不要忘記客戶端和服務器正在通信。 因此他們必須使用妥協的方式進行通信。 如果你喜歡存儲客戶信息,它必須是恆定的。 為此,您必須bind
其bind
到固定的localEndPoint
。
您還可以使用問題評論中的解決方案:您可以在消息中添加一個 id。 你也可以同時使用。
PS:我用Socket
類來代替TCPClient
或UDPClient
因為我發現他們尷尬和不一致的一些方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.