c++中实现websocket客户端和服务端
时间: 2023-11-01 11:07:34 浏览: 251
在C++中实现WebSocket客户端和服务端,通常需要使用第三方库来简化操作。以下是使用两个流行的C++ WebSocket库的示例代码:
1. 使用Boost.Beast库实现WebSocket客户端和服务端:
WebSocket客户端:
```c++
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <iostream>
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;
int main(int argc, char** argv) {
net::io_context ioc;
tcp::resolver resolver(ioc);
websocket::stream<tcp::socket> ws(ioc);
auto const results = resolver.resolve("echo.websocket.org", "80");
boost::asio::connect(ws.next_layer(), results.begin(), results.end());
ws.handshake("echo.websocket.org", "/");
ws.write(net::buffer(std::string("Hello, world!")));
beast::flat_buffer buffer;
ws.read(buffer);
std::cout << beast::make_printable(buffer.data()) << std::endl;
ws.close(websocket::close_code::normal);
}
```
WebSocket服务端:
```c++
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <iostream>
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;
int main(int argc, char** argv) {
net::io_context ioc;
tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 8080));
while (true) {
tcp::socket socket(ioc);
acceptor.accept(socket);
try {
websocket::stream<tcp::socket> ws(std::move(socket));
ws.accept();
beast::flat_buffer buffer;
ws.read(buffer);
ws.text(ws.got_text());
ws.write(buffer.data());
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
}
```
2. 使用Simple-Websocket-Server库实现WebSocket客户端和服务端:
WebSocket客户端:
```c++
#include "websocket.h"
int main(int argc, char** argv) {
auto client = std::make_shared<SimpleWeb::SocketClient<SimpleWeb::WS>>();
client->on_open = [](std::shared_ptr<SimpleWeb::SocketClient<SimpleWeb::WS>> client) {
std::cout << "Connected to server!" << std::endl;
client->send("Hello, world!");
};
client->on_message = [](std::shared_ptr<SimpleWeb::SocketClient<SimpleWeb::WS>> client, std::shared_ptr<SimpleWeb::WS::Message> message) {
std::cout << "Received message: " << message->string() << std::endl;
client->close();
};
client->connect("echo.websocket.org", 80);
}
```
WebSocket服务端:
```c++
#include "websocket.h"
int main(int argc, char** argv) {
auto server = std::make_shared<SimpleWeb::SocketServer<SimpleWeb::WS>>();
server->on_message = [](std::shared_ptr<SimpleWeb::SocketServer<SimpleWeb::WS>::Connection> connection, std::shared_ptr<SimpleWeb::WS::Message> message) {
std::cout << "Received message: " << message->string() << std::endl;
connection->send(message->string());
};
server->start();
}
```
请注意,这只是WebSocket客户端和服务端实现的基本示例。使用时需要根据实际需求进行修改和扩展。
阅读全文