C++ [UDP] 如何跟踪服务器上所有已连接(客户端)的套接字连接?
C++ [UDP] How to keep track of all connected(clients) socket connections on server?
我的服务器应该将它收到的消息转发给所有连接的客户端,但我的代码只能将消息发送回发件人。
struct User
{
char user_id[20];
string address;
struct sockaddr_in CONNECTED;
}U[8];
//USER LOGIN
for(int i = 0; i < 8; i++)
{
//DO THIS WHEN USER MATCHED
//user_id consists of Andrew, Lisa, David and etc
//so that each unique name has a unique connection(CONNECTED)
if(strcmp(user_id,U[i].user_id) == 0)
{
U[i].CONNECTED = cln_addr;
}
}
//AFTER RECEIVING THE MESSAGE FROM CLIENT, SEND THE MESSAGE BACK TO ALL CONNECTED CLIENTS
for(int i = 0; i < 8; i++)
{
sendto (*csock, BROADCASTMESSAGE, sizeof BROADCASTMESSAGE, 0, (struct sockaddr *)&U[i].CONNECTED, len_c_addr); //THIS HOWEVER ONLY FORWARD MESSAGE BACK TO THE SENDER
}
当您在服务器套接字中接受一个套接字时,将其存储在数组列表中。当该客户端消失时,将其从您的数组中删除。
使用此阵列,您可以向活动客户发送和广播数据。
我的服务器应该将它收到的消息转发给所有连接的客户端,但我的代码只能将消息发送回发件人。
struct User
{
char user_id[20];
string address;
struct sockaddr_in CONNECTED;
}U[8];
//USER LOGIN
for(int i = 0; i < 8; i++)
{
//DO THIS WHEN USER MATCHED
//user_id consists of Andrew, Lisa, David and etc
//so that each unique name has a unique connection(CONNECTED)
if(strcmp(user_id,U[i].user_id) == 0)
{
U[i].CONNECTED = cln_addr;
}
}
//AFTER RECEIVING THE MESSAGE FROM CLIENT, SEND THE MESSAGE BACK TO ALL CONNECTED CLIENTS
for(int i = 0; i < 8; i++)
{
sendto (*csock, BROADCASTMESSAGE, sizeof BROADCASTMESSAGE, 0, (struct sockaddr *)&U[i].CONNECTED, len_c_addr); //THIS HOWEVER ONLY FORWARD MESSAGE BACK TO THE SENDER
}
当您在服务器套接字中接受一个套接字时,将其存储在数组列表中。当该客户端消失时,将其从您的数组中删除。
使用此阵列,您可以向活动客户发送和广播数据。