C++ Boost Websocket Server Example
This example demonstrates how to create a simple WebSocket server using the Boost.Asio and Boost.Beast libraries in C++.
Prerequisites
Before running the example, ensure you have the following:
- Boost Library: Install Boost.Asio and Boost.Beast libraries.
- C++ Compiler: A C++ compiler compatible with Boost, such as g++ or Clang.
Code
#include
#include
#include
#include
#include
#include
using boost::asio::ip::tcp;
using boost::beast::websocket::stream;
using boost::beast::websocket::role_type;
using boost::beast::http::string_view;
using boost::beast::http::request;
using boost::beast::http::response;
using boost::beast::http::verb;
using boost::beast::http::status;
namespace net = boost::asio;
// This function handles the incoming connection and websocket communication.
void session(tcp::socket &socket) {
// Create a websocket stream object associated with the socket.
stream ws(socket);
try {
// Accept the websocket handshake.
ws.accept();
// Handle incoming messages.
while (true) {
boost::beast::flat_buffer buffer;
ws.read(buffer);
auto const &body = boost::beast::buffers_to_string(buffer.data());
std::cout << "Received message: " << body << std::endl;
// Send a response message.
ws.write(net::buffer(std::string("Echo: ") + body));
}
} catch (std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
int main() {
try {
// Create an io context object for asynchronous operations.
net::io_context ioc;
// Create a TCP acceptor object to listen for connections on port 8080.
tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 8080));
// Start accepting connections.
while (true) {
tcp::socket socket(ioc);
acceptor.accept(socket);
// Run the session function in a separate thread for each new connection.
std::thread(session, std::move(socket)).detach();
}
// Run the io context to handle asynchronous operations.
ioc.run();
} catch (std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
Explanation
- Initialization: The code starts by including necessary headers from the Boost.Asio and Boost.Beast libraries.
- Session Function: The
session
function handles each incoming connection.- Create WebSocket Stream: It creates a WebSocket stream object associated with the socket.
- Accept Handshake: It accepts the websocket handshake, establishing the connection.
- Receive and Process Messages: It continuously receives messages from the client, logs them, and echoes them back.
- Main Function: The
main
function sets up the server.- IO Context: An
io_context
object is created to handle asynchronous operations. - TCP Acceptor: A
tcp::acceptor
object is created to listen for connections on port 8080. - Accept Connections: The
main
function accepts new connections and spawns a new thread to handle each session. - Run IO Context: The
ioc.run()
call runs the IO context, allowing it to process asynchronous events and maintain the server.
- IO Context: An
Running the Example
- Compile the code:
g++ -o websocket_server websocket_server.cpp -lboost_system -lboost_thread -lboost_beast -lboost_asio
- Run the server:
./websocket_server
- Use a WebSocket client (like a browser or a WebSocket client library) to connect to
ws://localhost:8080
. - Send messages to the server, and observe the responses.
This example provides a basic framework for building a WebSocket server. You can extend it with various features like authentication, error handling, and more complex communication protocols.