是否可以在不保持套接字打开的情况下识别早期的 UDP 客户端?我想将一个整数 ID 链接到每个唯一的客户端,但我不想让任何其他线程保持打开状态。
//接收(服务器)
private static Int32 port = 11000;
private static UdpClient udpClient = new UdpClient(port);
public static void receive_threaded()
{
Thread t = new Thread(() =>
{
while (true)
{
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);
byte[] content = udpClient.Receive(ref remoteIPEndPoint);
if (content.Length > 0)
{
string message = Encoding.UTF8.GetString(content);
if (action_message_receive != null) action_message_receive(String.Format("Recv({0}): {1}", remoteIPEndPoint.Port, message));
parseMessage(message);
}
}
});
t.Start();
}
//发送(客户端)
private static void send_message(string ip, string message)
{
byte[] packetData = System.Text.UTF8Encoding.UTF8.GetBytes(message);
int port = 11000;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
if (action_message_send != null) action_message_send("Send: " + message);
}
客户端可以从服务器请求(临时)用户ID,服务器会将其添加到它的数据库中,并在完成时通知客户端。但是,我不能让客户端在发出请求时发送它自己的用户 ID,因为任何内存更改应用程序都意味着“黑客”可以访问其他用户的东西。
由于套接字不会保持打开状态,因此每次客户端向服务器发送某些内容时IPEndPoint.Port 都会发生变化,因此我无法对其进行跟踪。我可以通过在用户 ID 请求上创建用户名/传递并在此后涉及用户 ID 的每个请求上发送这些来完成它,但这很愚蠢。
那么有没有办法在不为每个客户端打开线程的情况下做到这一点?我可能在这里做一些非常奇怪的事情,因为 UDP 应该是单向街道,但我是来这里学习的,所以我只需要问。