C++实现websocket服务端客户端(基于boost,亲测可行!)

  整篇文章基本参考了https://blog.csdn.net/jianghuan0122/article/details/123528907,文章记录了如何在现有条件下实现该参考示例(参考示例存在报错,并且参考示例没有介绍环境安装,正确源码附于文末)

  自身环境:ubuntu18.04+gcc7.5.0+boost1.7,3

环境配置

  gcc或者g++一般都有,这里主要介绍一下boost的配置方法
  执行如下代码:

wget https://boostorg.jfrog.io/artifactory/main/release/1.73.0/source/boost_1_73_0.tar.bz2 --no-check-certificate
tar xvf boost_1_73_0.tar.bz2
cd boost_1_73_0
./bootstrap.sh --prefix=/usr 
./b2 
sudo ./b2 install
cat /usr/include/boost/version.hpp | grep "BOOST_LIB_VERSION"

  装完后发现还是会报错:#include <boost/beast/core.hpp> no such file
  这个时候再加一个:

sudo apt-get install libboost-all-dev

  然后编译执行代码就可以了,在这里说明下我不太确定是否要执行那个apt-get,理论上前面是源码编译就没问题了,后面估计是默认库的安装,但是我当时没太注意顺序,两个都做了一下才成功、
boost安装参考:https://blog.csdn.net/HandsomeHong/article/details/128813619

  还有就是参考的示例存在报错,是关于C++11codecvt部分的,没有时间去改bug了,就直接换了一套string和wstring的相互转化,主要参考了:https://blog.csdn.net/juluwangriyue/article/details/115680861
  这个需要加两个头文件#include #include

示例源码

server.cpp(需要换自己的IP)

#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>
#include <codecvt>
#include <wchar.h>
#include <locale.h>
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& str)
{
	std::wstring r;
    const char *source = str.c_str();
    wchar_t *dest = NULL;
    int len = 0;
    int ret = 0;
    len = strlen(source) + 1;
    if(len <= 1)
        return 0;
    dest = new wchar_t[len];
    ret = mbstowcs(dest, source, len);
    r = std::wstring(dest);
    delete[] dest;
	return r;
}

std::string wstring_to_string(const std::wstring& ws)
{
	std::string r = "";
    const wchar_t *source = ws.c_str();
    char *dest = NULL;
    int len = 0;
    int ret = 0;
    len = wcslen(source) + 1;
    if(len <= 1)
        return 0;
    dest = new char[len*sizeof(wchar_t)];
    ret = wcstombs(dest, source, len*sizeof(wchar_t));
    r = std::string(dest);
    delete[] dest;
	return r;
}

std::string ansi_to_utf8(const std::string& s)
{
	static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
	return conv.to_bytes(string_to_wstring(s));
}
std::string utf8_to_ansi(const std::string& s)
{
	static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
	return wstring_to_string(conv.from_bytes(s));
}
 
void do_session(tcp::socket& socket)
{
	try
	{
		websocket::stream<tcp::socket> 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(1); //等待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("192.168.1.116");//绑定ip地址
		auto const port = static_cast<unsigned short>(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;
	}
}

client.cpp(需要换自己的IP)

#include<time.h> 
 
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
#include <wchar.h>
#include <locale.h>
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& str)
{
	std::wstring r;
    const char *source = str.c_str();
    wchar_t *dest = NULL;
    int len = 0;
    int ret = 0;
    len = strlen(source) + 1;
    if(len <= 1)
        return 0;
    dest = new wchar_t[len];
    ret = mbstowcs(dest, source, len);
    r = std::wstring(dest);
    delete[] dest;
	return r;
}

std::string wstring_to_string(const std::wstring& ws)
{
	std::string r = "";
    const wchar_t *source = ws.c_str();
    char *dest = NULL;
    int len = 0;
    int ret = 0;
    len = wcslen(source) + 1;
    if(len <= 1)
        return 0;
    dest = new char[len*sizeof(wchar_t)];
    ret = wcstombs(dest, source, len*sizeof(wchar_t));
    r = std::string(dest);
    delete[] dest;
	return r;
}

std::string ansi_to_utf8(const std::string &s)
{
	static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
	return conv.to_bytes(string_to_wstring(s));
}
std::string utf8_to_ansi(const std::string& s)
{
	static std::wstring_convert<std::codecvt_utf8<wchar_t> > 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<tcp::socket> ws{ ioc };
		auto const address = net::ip::make_address("192.168.1.116"); //服务器地址
		auto const port = static_cast<unsigned short>(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("192.168.1.116", "/"); //发送握手消息
		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 << "个"<<std::endl;
			}			
		}
	
		ws.close(websocket::close_code::normal);// 关闭WebSocket连接
	}
	catch (std::exception const& e)
	{
		std::cerr << "Error: " << e.what() << std::endl;
		return EXIT_FAILURE;
	}
	return EXIT_SUCCESS;
}

编译的命令如下:

g++ server.cpp -o server -lpthread -std=c++11
g++ client.cpp -o client -std=c++11 -lpthread

你可能感兴趣的:(websocket,c++,websocket,网络)