boost非阻塞 websocket连接

#include <iostream>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/spawn.hpp>
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace websocket = beast::websocket;
using tcp = asio::ip::tcp;

void on_connect(const boost::system::error_code& ec,
	tcp::socket socket,
	websocket::stream<tcp::socket> ws,
	UCHAR pIndex,
	asio::yield_context yield) {
	if (ec) {
		std::cerr << "Connect error: " << ec.message() << std::endl;
		return;
	}
	try {
		// Perform WebSocket handshake
		ws.async_handshake("192.168.122.1", "/websocket", yield);

		while (1) {
			std::string sendStr = "Hello, WebSocket!index:" + std::to_string(pIndex);
			// Send a message
			ws.async_write(asio::buffer(sendStr), yield);

			// Receive a message
			beast::flat_buffer buffer;
			ws.async_read(buffer, yield);

			std::cout << "index:" << std::to_string(pIndex) << ", Received: " << beast::make_printable(buffer.data()) << std::endl;
		}
		// Close the WebSocket connection
		ws.async_close(websocket::close_code::normal, yield);
	}
	catch (const std::exception& e) {
		std::cerr << "Error: " << e.what() << std::endl;
	}
}

int main() {

	asio::io_context io_context;
	tcp::resolver resolver(io_context);

	auto endpoints = resolver.resolve("192.168.122.1", "8080");

	for (UCHAR i = 0; i < 3; i++) {
		asio::spawn(io_context, [&, endpoints, i](asio::yield_context yield) {
			UCHAR vIndex = i;
			tcp::socket socket(io_context);
			websocket::stream<tcp::socket> ws(std::move(socket));
			boost::system::error_code ec;
			asio::async_connect(ws.next_layer(), endpoints, yield[ec]);
			asio::spawn(io_context, [&](asio::yield_context yield) {
				on_connect(ec, std::move(socket), std::move(ws), vIndex, yield);
				});
			});
	}
	io_context.run();


	return 0;
}

posted @ 2024-01-15 13:33  狂客  阅读(132)  评论(0编辑  收藏  举报