【发布时间】:2014-09-19 00:52:40
【问题描述】:
我正在尝试实现一个多线程 UDP 服务器,其中每个线程服务一个客户端。 到目前为止,客户端已正确注册,并且客户端正在接收数据。为了使其可靠,我尝试在特定时间间隔内未收到消息时发送否定确认。
此确认在服务器端 recvfrom() 函数中被视为来自新客户端的请求。我如何区分服务器端的两者?是否有任何与发送和接收相关的函数可以做同样的事情?
代码在 c 中,我使用 pthreads 来实现线程功能。我已经使用基本的 sendto() 和 recvfrom() 套接字函数来实现相同的功能。
代码大纲:
At the server side:
recvfrom()
when received:
Add to client list
create thread:
send data in the thread function
exit thread
At the client side:
sendto() -> to initiate the request to the server
when time < timeout
recvfrom() -> receive the data from the server
when timeout occurs
sendto() -> send negative acknowledgement.
【问题讨论】:
-
在您的 UDP 数据前面放置一个命令代码,表明它是什么类型的消息。一个字节可能就足够了。
-
如何在服务器端区分相同的?使用从客户端收到的消息的长度?
-
如果你想要一个可靠的、面向连接的数据报协议,你有两个选择。向 TCP 添加数据报层,或尝试向 UDP 添加可靠性和连接。第一个选择要容易得多。
-
否定确认可能是从服务器端还是客户端发送? UDP 是不可靠的通信,因此可能会丢失数据包。当第一个数据包丢失时,客户端什么都不知道,也不能做任何事情。同样,服务器无法知道第一个数据包是否到达客户端,因此服务器无能为力。您的系统需要某种确认机制。
-
问题是,当我尝试实现确认机制时,确认的消息被解释为新的客户端请求。确认消息未到达为该特定客户端提供服务的相应服务器线程。
标签: c multithreading sockets udp pthreads