C/C++ 实现的websocket客户端和服务器

领导安排实现一个websocket客户端做测试用,因为工位电脑上的环境只有vs2019和boost1.78.0,所以只能基于boost.beast开发。

擅长Qt并且有Qt开发环境的用QWebsocket更方便。

官方的example中仅仅输出到控制台,而且不支持中文,这里我加入了ansi到utf8的转换,使用utf8就能正常解析中文。

注:项目需包含boost库

C/C++ 实现的websocket客户端和服务器_第1张图片

客户端代码:

#include 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
namespace beast = boost::beast;         // from 
namespace http = beast::http;           // from 
namespace websocket = beast::websocket; // from 
namespace net = boost::asio;            // from 
using tcp = boost::asio::ip::tcp;       // from 
std::wstring string_to_wstring(const std::string &s)
{
	using default_convert = std::codecvt;
	static std::wstring_convertconv(new default_convert("CHS"));
	return conv.from_bytes(s);
}
std::string wstring_to_string(const std::wstring &s)
{
	using default_convert = std::codecvt;
	static std::wstring_convertconv(new default_convert("CHS"));
	return conv.to_bytes(s);
}
std::string ansi_to_utf8(const std::string &s)
{
	static std::wstring_convert > conv;
	return conv.to_bytes(string_to_wstring(s));
}
std::string utf8_to_ansi(const std::string& s)
{
	static std::wstring_convert > conv;
	return wstring_to_string(conv.from_bytes(s));
}

int main(int argc, char** argv)
{
	int num = 0;//接收到包的个数

	try
	{
		net::io_context ioc;
		tcp::resolver resolver{ ioc };
		websocket::stream ws{ ioc };
		auto const address = net::ip::make_address("10.73.0.170"); //服务器地址
		auto const port = static_cast(std::atoi("20000"));//服务器端口号
		tcp::endpoint endpoint{ address, port };
		auto const results = resolver.resolve(endpoint);
		// 在我们从查找中获得的IP地址上建立连接
		net::connect(ws.next_layer(), results.begin(), results.end());
		ws.set_option(websocket::stream_base::decorator(
			[](websocket::request_type& req)
		{
			req.set(http::field::user_agent,
				std::string(BOOST_BEAST_VERSION_STRING) +
				" websocket-client-coro");
		}));

		ws.handshake("10.73.0.170", "/"); //发送握手消息
		while (true)
		{
			beast::flat_buffer buffer;//创建一个缓冲区用于存放接收到的消息	
			ws.read(buffer);// 读取一条消息到缓冲区
			std::string out;
			out = beast::buffers_to_string(buffer.cdata());
			std::cout << utf8_to_ansi(out) << std::endl; //输出消息到控制台显示

			//解析json数据包
			if (out != "") //未解析json,只是判断内容是否为空
			{		
				std::string text = "{\"result\": 0}";//发送的消息内容,以一个json数据包的格式
				ws.write(net::buffer(ansi_to_utf8(text))); // 发送消息

				num++;//增加计数

				//当前时间
				time_t now = time(NULL);
				tm* tm_t = localtime(&now);
				std::stringstream ss;
				ss << tm_t->tm_year + 1900 << "-" << tm_t->tm_mon + 1 << "-" << tm_t->tm_mday
					<< " " << tm_t->tm_hour << ":" << tm_t->tm_min << ":" << tm_t->tm_sec;

				std::cout << "当前时间:" << ss.str() << ",第 " << num << "个"<

服务器代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
namespace beast = boost::beast;         // from 
namespace http = beast::http;           // from 
namespace websocket = beast::websocket; // from 
namespace net = boost::asio;            // from 
using tcp = boost::asio::ip::tcp;       // from 
std::wstring string_to_wstring(const std::string& s)
{
	using default_convert = std::codecvt;
	static std::wstring_convertconv(new default_convert("CHS"));
	return conv.from_bytes(s);
}
std::string wstring_to_string(const std::wstring& s)
{
	using default_convert = std::codecvt;
	static std::wstring_convertconv(new default_convert("CHS"));
	return conv.to_bytes(s);
}
std::string ansi_to_utf8(const std::string& s)
{
	static std::wstring_convert > conv;
	return conv.to_bytes(string_to_wstring(s));
}
std::string utf8_to_ansi(const std::string& s)
{
	static std::wstring_convert > conv;
	return wstring_to_string(conv.from_bytes(s));
}

void do_session(tcp::socket& socket)
{
	try
	{
		websocket::stream ws{ std::move(socket) };
		ws.set_option(websocket::stream_base::decorator(
			[](websocket::response_type& res)
		{
			res.set(http::field::server,
				std::string(BOOST_BEAST_VERSION_STRING) +
				" websocket-server-sync");
		}));
		ws.accept();//等待客户端连接
		for (;;)
		{
			std::string text = "{\"send\": 123}"; // 发送的消息内容,以一个json数据包的格式	
			ws.write(net::buffer(ansi_to_utf8(text)));// 发送消息
		
			beast::flat_buffer buffer;// 这个缓冲区将保存传入的消息
			ws.read(buffer);// 读取一条消息
			auto out = beast::buffers_to_string(buffer.cdata());
			std::cout << utf8_to_ansi(out) << std::endl;

			Sleep(1000); //等待1秒

			/*
			// 将读取到的消息再发送回客户端
			ws.text(ws.got_text());
			ws.write(buffer.data());
			*/
		}
	}
	catch (beast::system_error const& se)
	{
		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
	{
		auto const address = net::ip::make_address("10.73.0.170");//绑定ip地址
		auto const port = static_cast(std::atoi("20000"));//绑定端口号
		net::io_context ioc{ 1 };
		tcp::acceptor acceptor{ ioc,{ address, port } };
		for (;;)
		{
			tcp::socket socket{ ioc };
			acceptor.accept(socket);
			// 开启线程等待客户端的连接请求
			std::thread{ std::bind(&do_session,std::move(socket)) }.detach();
		}
	}
	catch (const std::exception & e)
	{
		std::cerr << "Error: " << e.what() << std::endl;
		return EXIT_FAILURE;
	}
}

联调效果:

C/C++ 实现的websocket客户端和服务器_第2张图片

你可能感兴趣的:(C++,websocket,网络协议,网络)