Reputation: 4273
I have the client written in Javascript and it works great. Server code works as well. However I don't know how to send messages from the server to the client, or how to end a connection. Does anyone know how to do that ? Also, since I am a complete beginner, is anything that I am missing in my code ? I tried to keep it as simple as possible.
#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();
}
Upvotes: 4
Views: 6264
Reputation: 107
I made this based off one of the issue logs :
server::connection_ptr con = s.get_con_from_hdl(hdl);
std::string resp("BAD");
con->send(resp, websocketpp::frame::opcode::text);
for anyone needing to check out a binary response : https://github.com/zaphoyd/websocketpp/issues/572
Upvotes: 3
Reputation: 5353
If you're still struggling with that code, there's another great C++ WebSocket library here that might be easier for you to use, its header-only and uses just boost. It comes with example code and documentation: http://vinniefalco.github.io/
Here's a complete program that sends a message to the echo server:
#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";
}
Upvotes: 4