0%

Socket.io-client-cpp 安装使用与放弃

  1. 安装
  2. 编写简单类

socketio/socket.io-client-cpp: C++11 implementation of Socket.IO client (github.com)

安装

使用vcpkg安装

1
vcpkg install socket-io-client

编写简单类

SocketIO.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#pragma once
#include <sio_client.h>

class SocketIO
{
public:
SocketIO();

protected:
// 开始监听时触发,全局一次
void OnListen();
void OnFailListen();
void OnCloseListen(sio::client::close_reason reason);

// socket连接建立后触发:受网络影响,可能多次建立连接
void OnSocketOpen(std::string const& nsp);

void OnSocketClose(std::string const& nsp);


/***************************************************
* 自定义消息响应函数
****************************************************/
private:
void OnData(sio::event ev);

private:
sio::client m_client;
};

SocketIO.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/************************************************************
* socket.io-client-cpp 无法接收 binary 数据,望周知
************************************************************/

#include "SocketIO.h"
#include <functional>
#include <sstream>
#include <Windows.h>

SocketIO::SocketIO()
{
m_client.connect("http://127.0.0.1:8888");

m_client.set_open_listener(std::bind(&SocketIO::OnListen, this));
m_client.set_fail_listener(std::bind(&SocketIO::OnFailListen, this));
m_client.set_close_listener(std::bind(&SocketIO::OnCloseListen, this, std::placeholders::_1));

m_client.set_socket_open_listener(std::bind(&SocketIO::OnSocketOpen, this, std::placeholders::_1));
m_client.set_socket_close_listener(std::bind(&SocketIO::OnSocketClose, this, std::placeholders::_1));
}

void SocketIO::OnListen()
{
std::stringstream ss;
ss << __FUNCTION__ << " OnListen" << std::endl;
OutputDebugString(ss.str().c_str());

auto& socket = m_client.socket("/nap-hub");

socket->emit("hello", sio::string_message::create("hello, /nap-hub"));

socket->on("data", std::bind(&SocketIO::OnData, this, std::placeholders::_1));
}

void SocketIO::OnFailListen()
{
std::stringstream ss;
ss << __FUNCTION__ << " OnFailListen" << std::endl;
OutputDebugString(ss.str().c_str());
}

void SocketIO::OnCloseListen(sio::client::close_reason reason)
{
std::stringstream ss;
ss << __FUNCTION__ << " OnCloseListen: " << reason << std::endl;
OutputDebugString(ss.str().c_str());
}

void SocketIO::OnSocketOpen(std::string const& nsp)
{
std::stringstream ss;
ss << __FUNCTION__ << " OnSocketOpen: " << nsp << std::endl;
OutputDebugString(ss.str().c_str());
}

void SocketIO::OnSocketClose(std::string const& nsp)
{
std::stringstream ss;
ss << __FUNCTION__ << " SOCKET Close: " << nsp << std::endl;
OutputDebugString(ss.str().c_str());
}

void SocketIO::OnData(sio::event ev)
{
std::stringstream ss;
ss << __FUNCTION__ << " : " << ev.get_name() << "," << ev.get_message()->get_string() << std::endl;
OutputDebugString(ss.str().c_str());
}