Websocket服务端和客户端通信(WSS、WS)

前端和后端之间的通讯

一、简介

前端为客户端(Client),后端为服务端(Server)
具体操作步骤为:
1.运行 Server 目录下的 --> WebsocketServerWss_Ws.exe
2.打开浏览器输入 --> https://localhost:8282 会提示此连接不受信任
3.点击 我已充分了解可能的风险 --> 添加例外 --> 确认安全例外
4.运行 Client 目录下的 --> WebsocketClient.html
5.在消息框里面写入消息 点击发送就可以在 Server\Log里面查看收到的消息了

二、运行效果

WebsocketClient.html
Websocket服务端和客户端通信(WSS、WS)_第1张图片
WebsocketServerWss_Ws.exe
Websocket服务端和客户端通信(WSS、WS)_第2张图片

三、部分代码

1. WebsocketClient.html


<html>
<title>---WebscoketClient---title>
<meta charset="utf-8">

<style>
	.parent{
		#background:red;
		#height:100px;
	}
	.child{
		background:blue;
		position:relative;
		z-index:-1;
	}
style>

<div class="parent">
	<label>IP地址label>
	<input   id="serverurl1" value="ws://localhost" />
	<label>端口label>
	<input   id="port1" value="8686" />
	<br/>
	<br/>
	<label>消息label>
	
	

2. Websocket.cpp

#include "stdafx.h"
#include "Websocket.h"
#include "NetilerLog.h"
#include "NetilerIni.h"
#include "StringUtil.h"
#include "json.h"
#include 
#include 
#include 
#include 
#include 


typedef websocketpp::server<websocketpp::config::asio> server_plain;
typedef websocketpp::server<websocketpp::config::asio_tls> server_tls;

using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

typedef websocketpp::lib::shared_ptr<boost::asio::ssl::context> context_ptr;

server_plain endpoint_plain;			// ws
server_tls endpoint_tls;				// wss
boost::asio::io_service ioserver;


CWebsocket::CWebsocket(HWND hwnd)
{
	m_hwnd =  hwnd;
}

CWebsocket::~CWebsocket(void)
{

}


// 连接成功
template <typename EndpointType>
void OnOpen(EndpointType* s, websocketpp::connection_hdl hdl)
{
	websocketpp::lib::error_code errorCode;

	s->send(hdl, "Receive from Client message...", websocketpp::frame::opcode::TEXT, errorCode);
	if (!errorCode)
	{
		NETILER_DEBUG_FMT("发送数据到客户端成功!");
	}
	else
	{
		NETILER_ERROR_FMT("发送数据到客户端失败, 【%s】", errorCode.message().c_str());
	}
}


// 收到消息
template <typename EndpointType>
void OnMessage(EndpointType* s, websocketpp::connection_hdl hdl, typename EndpointType::message_ptr msg)
{

	NETILER_INFO_FMT("Websocket收到来自客户端的消息...");
	char str_message[1024] = "";
	const char * pszmsg = (const char *)(msg->get_payload().c_str());
	std::string strmsg = StringUtil::UTF82GBK(pszmsg);
	NETILER_DEBUG_FMT("消息为 = 【%s】", strmsg.c_str());

}

// 获取密码
std::string GetPassword()
{
	return "test";
}


// TLS初始化
context_ptr OnTlsInit(websocketpp::connection_hdl hdl) 
{
	std::cout << "on_tls_init called with hdl: " << hdl.lock().get() << std::endl;
	context_ptr ctx(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1));

	try {
		ctx->set_options(boost::asio::ssl::context::default_workarounds |
			boost::asio::ssl::context::no_sslv2 |
			boost::asio::ssl::context::no_sslv3 |
			boost::asio::ssl::context::single_dh_use);
		ctx->set_password_callback(bind(&GetPassword));
		ctx->use_certificate_chain_file("server.pem");
		ctx->use_private_key_file("server.pem", boost::asio::ssl::context::pem);
	} catch (std::exception& e) {
		std::cout << e.what() << std::endl;
	}
	return ctx;
}

// 打开 websocket
BOOL CWebsocket::OpenWebsocket()
{
	
	/*             ws协议          */
	int WsPort = NetilerIni::GetSectionKeyUint("Websocket_WS", "port");
	endpoint_plain.init_asio(&ioserver);
	endpoint_plain.set_message_handler(bind(&OnMessage<server_plain>,&endpoint_plain,::_1,::_2));
	endpoint_plain.listen(WsPort);
	endpoint_plain.start_accept();
	NETILER_INFO_FMT("Websocket_WS 启动成功 --> 端口为:【%d】", WsPort);

	/*             wss协议          */
	int WssPort = NetilerIni::GetSectionKeyUint("Websocket_WSS", "port");
	endpoint_tls.init_asio(&ioserver);
	endpoint_tls.set_tls_init_handler(bind(&OnTlsInit,::_1));
	endpoint_tls.listen(WssPort);
	endpoint_tls.set_open_handler(bind(&OnOpen<server_tls>, &endpoint_tls, ::_1));
	endpoint_tls.set_message_handler(bind(&OnMessage<server_tls>, &endpoint_tls, ::_1, ::_2));
	endpoint_tls.start_accept();
	NETILER_INFO_FMT("Websocket_WSS 启动成功 --> 端口为:【%d】", WssPort);

	// Start the ASIO io_service run loop running both endpoints
	ioserver.run();

	return 0;
}


void CWebsocket::CloseWebsocket()
{
	NETILER_INFO_FMT("Websocket 服务关闭!");
	if (endpoint_plain.is_listening())
	{
		endpoint_plain.stop_listening();
	}

	if (endpoint_tls.is_listening())
	{
		endpoint_tls.stop_listening();
	}
	ioserver.stop();

}

你可能感兴趣的:(Websocket,c++,html,html5,websocket,socket)