我的客户端是用 Javascript 编写的,效果很好。服务器代码也能正常工作。但是我不知道如何从服务器向客户端发送消息,或者如何结束连接。有谁知道这是怎么做到的吗 ?另外,由于我是一个完全的初学者,我的代码中是否遗漏了什么?我尽量保持简单。
#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> server;
void on_message(websocketpp::connection_hdl hdl, server::message_ptr msg)
{
std::cout << "Message received:" << std::endl;
std::cout << msg->get_payload() << std::endl;
}
int main()
{
server s;
s.set_message_handler(&on_message);
s.init_asio();
s.listen(57252);
s.start_accept();
std::cout << "Server Started." << std::endl;
s.run();
}
最佳答案
如果您仍在为该代码苦苦挣扎,这里还有另一个很棒的 C++ WebSocket 库,您可能更容易使用它,它仅包含 header 并且仅使用 boost。它带有示例代码和文档: http://vinniefalco.github.io/
这是一个向回显服务器发送消息的完整程序:
#include <beast/websocket.hpp>
#include <beast/buffers_debug.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <string>
int main()
{
// Normal boost::asio setup
std::string const host = "echo.websocket.org";
boost::asio::io_service ios;
boost::asio::ip::tcp::resolver r(ios);
boost::asio::ip::tcp::socket sock(ios);
boost::asio::connect(sock,
r.resolve(boost::asio::ip::tcp::resolver::query{host, "80"}));
using namespace beast::websocket;
// WebSocket connect and send message using beast
stream<boost::asio::ip::tcp::socket&> ws(sock);
ws.handshake(host, "/");
ws.write(boost::asio::buffer("Hello, world!"));
// Receive WebSocket message, print and close using beast
beast::streambuf sb;
opcode op;
ws.read(op, sb);
ws.close(close_code::normal);
std::cout <<
beast::debug::buffers_to_string(sb.data()) << "\n";
}
关于c++ - 如何使用 Websocketpp 发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36582675/