【发布时间】:2019-10-13 21:58:15
【问题描述】:
当多个客户端向服务器发送数据包时,我如何编写代码以在其相应的子线程上接收它们,而不是在主进程上接收它们
我正在使用线程为 udp 客户端和服务器编写 c 程序,因此如果我连接了 4 个客户端,将创建 4 个线程,每个线程将发送一些数据。收到数据后,客户端会发送确认,但问题是这些确认应该由相应的线程接收,但是
我在主进程中有receivefrom函数来监听新客户端,我也有线程上的receivefrom函数来获取ack数据包但是这些来自客户端的ack将进入主进程而不是进入线程请帮助我提前谢谢
我的代码 服务器代码
//created udp socket
// binded
while(1)
{
// to receive new connections
n=recvfrom(sock,buffer,512,0,(struct sockaddr*)&from,&length);
// if some client sent request i will assign new thread to serve it
pthread_create(&thread_id[str_cnt], NULL, serve,(void*)(&cli[str_cnt]));
}
function serve(args)
{
while(1)
{
// sendind data to that client
sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr,clientlen);
//now wating for ack from the client
sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr,clientlen);
}
}
}
【问题讨论】:
-
欢迎来到 SO。如果您向我们展示代码,就可以更轻松地提出您需要的建议。
-
@Gerhardh 请帮帮我
-
数据包是从 main 函数中的 recv from() 接收的,而不是从线程上的 recvfrom() 函数接收的
-
这些是相当不完整的sn-ps。请提供MCVE 并查看How to ask
-
在这种情况下通常使用线程来读取来自客户端的连接。使用 UDP,您没有连接,也无法在线程中读取,因为所有客户端数据都在同一个套接字上接收。
标签: c multithreading sockets udp