[英]Datagram Unix domain socket with Boost.Asio
我正在努力接收使用带有Boost.Asio的数据报Unix套接字的同步客户端代码的数据。
服务器似乎工作正常,因为如果我用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);
问题是你只设置了发送端。
要同时接收相同的套接字,您需要绑定到文件名,就像在服务器端一样。 这是代码最后几行的修改版本:
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
,但是当然这会限制你只有一个客户端,直到你改变它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.