之前工作中用到websocket,用boost.beast实现了客户端,原则上可以用了。不过既然涉及到这个问题,于是顺便研究了一下服务端如何实现。下面同样给出同步的版本和异步的版本。
先看看同步的版本
server.cpp
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <thread>
using tcp = boost::asio::ip::tcp;
namespace websocket = boost::beast::websocket;
// echoes back all received WebSocket messages
void do_session(tcp::socket& socket)
{
try {
// Construct the stream by moving in the socket
websocket::stream<tcp::socket> ws{std::move(socket)};
// Accept the websocket handshake
ws.accept();
for (;;) {
// This buffer will hold the incoming message
boost::beast::multi_buffer buffer;
// Read a message
ws.read(buffer);
// Echo the message back
ws.text(ws.got_text());
ws.write(buffer.data());
}
} catch (boost::system::system_error const& se) {
// This indicates that the session was closed
if (se.code() != websocket::error::closed)
std::cerr << "Error: " << se.code().message() << std::endl;
} catch (std::exception const& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
int main(int argc, char* argv[])
{
try {
// Check command line arguments
if (argc != 3) {