gpt4 book ai didi

c - UDP 多套接字接收数据并高效处理 - C & Linux

转载 作者:太空狗 更新时间:2023-10-29 11:22:38 26 4
gpt4 key购买 nike

我必须从 15 个不同的客户端接收数据,每个客户端都在 5 个不同的端口上发送数据。共15个*5 socket 。

对于每个客户端端口号是定义和固定的。例如客户端 1,端口 3001 到 3005。客户端 2,端口 3051 到 3055 等。它们有一个共同点,即第一个端口(3001、3051)用于发送命令。其他端口发送一些数据。

收到数据后,我必须检查校验和。跟踪recvd数据包,如果丢失则重新请求数据包并且还必须写入硬盘上的文件。

限制 我无法更改上述设计,也无法从 UDP 更改为 TCP。阅读后我知道的两种方法是

  • 使用 select() 的异步多路复用。
  • 每个插槽的线程数。

我尝试了第一个,但在获取数据时卡住了。我能够接收数据。我有一些处理要做,所以我想为每个套接字启动一个线程(或)让套接字处理(比如所有第一个端口,所有第二个端口,等等..i.e.3001,3051等)但是在这里,如果客户端发送任何数据,那么 FD_ISSET 变为 true,所以如果我启动一个线程,那么它就成为每条消息的线程。问题:如何在此处添加线程代码,比如说,如果我在 if(FD_ISSET ..) 中包含 pthread_create,那么对于我收到的每条消息,我都会创建一个线程。但我想要每个套接字一个线程。

  while(1)
{
int nready=0;
read_set = active_set;

if((nready = select(fdmax+1,&read_set,NULL,NULL,NULL)) == -1)
{
printf("Select Errpr\n");
perror("select");
exit(EXIT_FAILURE);
}
printf("number of ready desc=%d\n",nready);

for(index=1;index <= 15*5;index++)
{
if(FD_ISSET(sock_fd[index],&read_fd_set))
{
rc = recvfrom(sock_fd[index],clientmsgInfo,MSG_SIZE,0,
(struct sockaddr *)&client_sockaddr_in,
&sockaddr_in_length);
if(rc < 0)
printf("socket %d down\n",sock_fd[index]);

printf("Recieved packet from %s: %d\nData: %s\n\n", inet_ntoa(client_sockaddr_in.sin_addr), ntohs(client_sockaddr_in.sin_port), recv_client_message);
}
} //for
} //while

最佳答案

在程序启动时创建线程,并将它们划分为处理数据、命令等

如何?

1. lets say you created 2 threads, one for data and another for the commands.
2. make them sleep in the thread handler or let them wait on a lock that the main thread
acquired, seems to be that mainthread got two locks one for each of them.
3. when any client data or command that got into the recvfrom at mainthread, depending on the
type of the buffer(data, commands), copy the buffer into the shared data by mainthread and
other threads and unlock the mutex.
4. at threads lock the mutex so that mainthread wont' corrupt the data and once processing is
done at the threads unlock and sleep.

更好的办法是有一个队列,它由主线程填满并且可以被其他线程明智地访问元素。

关于c - UDP 多套接字接收数据并高效处理 - C & Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15859890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com