2012-10-02 63 views
3

我很努力接收数据与同步客户端代码使用数据报Unix套接字与Boost.Asio。数据报Unix域套接字与Boost.Asio

该服务器似乎工作正常,因为如果我连接到它与netcat我收到数据。但是,尝试使用下面的代码时,它会卡在receive_from()中。 strace显示receive_from()系统调用被调用,但没有收到任何内容,而strace在服务器上显示正尝试向客户端发送数据,但未能这样做。

boost::asio::io_service io_service; 

boost::asio::local::datagram_protocol::socket socket(io_service); 
socket.open(); 

cmd::cmd cmd; 
cmd.type = cmd::cmdtype::request; 
cmd.id = cmd::cmdid::dumptop; 

boost::asio::local::datagram_protocol::endpoint receiver_endpoint("socket.unix"); 

/* The server receives this data successfully */ 
socket.send_to(
    boost::asio::buffer(reinterpret_cast<char*>(&cmd), 
    sizeof(cmd)), 
    receiver_endpoint 
); 

boost::array<char, 128> recv_buf; 
boost::asio::local::datagram_protocol::endpoint ep; 

/* When the server sends data, nothing is received here. 
    Maybe it's an issue with the endpoint??? */ 
size_t len = socket.receive_from(
    boost::asio::buffer(recv_buf), ep); 
+1

可能值得在客户端和服务器上发布strace输出的相关部分。 – cmeerw

+0

没有如receive_from()系统调用。你的意思是recv(2)? –

回答

0

问题是你只设置了发送端。

若要通过同一套接字接收,则需要绑定到文件名,就像在服务器端一样。这里是你的代码的最后几行的修改版本:

boost::array<char, 128> recv_buf; 
boost::asio::local::datagram_protocol::endpoint ep("socket.unix.client"); 
// bind to the previously created and opened socket: 
socket.bind(ep); 

/* now get data from the server */ 
size_t len = socket.receive_from(
    boost::asio::buffer(recv_buf), ep); 

通常的成语是服务器(在你的代码socket.unix)有一个著名的文件名和每个通信客户端创建自己独特的名字通过做一些像附加自己的PID一样的东西。为简单起见,此示例仅使用socket.unix.client,但当然这会限制您只有一个客户端,直到您更改为止。