我正在尝试使用TCP从客户端和服务器发送和接收消息。我正在尝试使用线程,我根本不知道如何执行此操作。我可以很好地连接到服务器,但我需要能够根据需要从两个地方发送和接收消息。我一直在搜索几个小时并且空洞,因为Google上的所有结果都过于复杂和混乱。
struct Client
{
boost::asio::ip::tcp::socket socket;
Client(const char* host = HOST, const char* port = PORT) : socket(io_service)
{
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query(HOST, PORT));
boost::asio::connect(this->socket, endpoint);
};
};
这就是我到目前为止为客户所做的一切。
对于服务器:
const int PORT = 52275;
int main()
{
try
{
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), PORT));
{
boost::asio::ip::tcp::socket socket(io_service);
acceptor.accept(socket);
main();
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
}
答案 0 :(得分:9)
因为假设您只想以最简单的方式发送/任何/消息,显然是安全的:
<强> Live On Coliru 强>
#include <boost/asio.hpp>
struct Client
{
boost::asio::io_service& io_service;
boost::asio::ip::tcp::socket socket;
Client(boost::asio::io_service& svc, std::string const& host, std::string const& port)
: io_service(svc), socket(io_service)
{
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query(host, port));
boost::asio::connect(this->socket, endpoint);
};
void send(std::string const& message) {
socket.send(boost::asio::buffer(message));
}
};
#include <iostream>
static const int PORT = 52275;
void client_thread() {
boost::asio::io_service svc;
Client client(svc, "127.0.0.1", std::to_string(PORT));
client.send("hello world\n");
client.send("bye world\n");
}
void server_thread() {
try
{
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), PORT));
{
boost::asio::ip::tcp::socket socket(io_service);
acceptor.accept(socket);
boost::asio::streambuf sb;
boost::system::error_code ec;
while (boost::asio::read(socket, sb, ec)) {
std::cout << "received: '" << &sb << "'\n";
if (ec) {
std::cout << "status: " << ec.message() << "\n";
break;
}
}
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
}
#include <boost/thread.hpp>
int main() {
boost::thread_group tg;
tg.create_thread(server_thread);
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
tg.create_thread(client_thread);
tg.join_all();
}