websocketpp 最简单的客户端 一

Posted qianbo_insist

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了websocketpp 最简单的客户端 一相关的知识,希望对你有一定的参考价值。

websocket 服务端

简单服务端在这里

websocketpp 客户端

客户端并没有做断线重连,这个有兴趣的可以自己实现,下一章会实现的。几个预定义的还是要写,例如不想用boost,直接用asio,还是要定义ASIO_STANDALONE,其他的太简单,多熟悉官方的例子就好


#define _CRT_SECURE_NO_WARNINGS
#define _WEBSOCKETPP_CPP11_TYPE_TRAITS_
#define _SCL_SECURE_NO_WARNINGS
#define ASIO_STANDALONE
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <iostream>

typedef websocketpp::client<websocketpp::config::asio_client> client;

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

// pull out the type of messages sent by our config
typedef websocketpp::config::asio_client::message_type::ptr message_ptr;

// This message handler will be invoked once for each incoming message. It
// prints the message and then sends a copy of the message back to the server.
void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg) {
	std::cout << "on_message called with hdl: " << hdl.lock().get()
		<< " and message: " << msg->get_payload()
		<< std::endl;


	websocketpp::lib::error_code ec;

	c->send(hdl, msg->get_payload(), msg->get_opcode(), ec);
	if (ec) {
		std::cout << "Echo failed because: " << ec.message() << std::endl;
	}
}

int main(int argc, char* argv[]) {
	// Create a client endpoint
	client c;

	std::string uri = "ws://localhost:9002";

	if (argc == 2) {
		uri = argv[1];
	}

	try {
		// Set logging to be pretty verbose (everything except message payloads)
		c.set_access_channels(websocketpp::log::alevel::all);
		c.clear_access_channels(websocketpp::log::alevel::frame_payload);

		// Initialize ASIO
		c.init_asio();

		// Register our message handler
		c.set_message_handler(bind(&on_message, &c, ::_1, ::_2));

		websocketpp::lib::error_code ec;
		client::connection_ptr con = c.get_connection(uri, ec);
		if (ec) {
			std::cout << "could not create connection because: " << ec.message() << std::endl;
			return 0;
		}

		// Note that connect here only requests a connection. No network messages are
		// exchanged until the event loop starts running in the next line.
		c.connect(con);

		// Start the ASIO io_service run loop
		// this will cause a single connection to be made to the server. c.run()
		// will exit when this connection is closed.
		c.run();
	}
	catch (websocketpp::exception const & e) {
		std::cout << e.what() << std::endl;
	}
}

以上是关于websocketpp 最简单的客户端 一的主要内容,如果未能解决你的问题,请参考以下文章

译丨Yarn - Javascript 新一代套件管理

使用 websocketpp 时“调用绑定没有匹配的函数”

websocketpp asio监听错误

WebRTC笔记之二十一:基于WebSocketPP的Janus客户端

如何使用 websocket websocketpp 发送和接收消息?

WebRTC笔记之十九:基于WebSocketPP的TLS客户端和服务器