国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - C/C++ - C++編寫的WebSocket服務端客戶端實現示例代碼

C++編寫的WebSocket服務端客戶端實現示例代碼

2022-02-16 15:55kagula086 C/C++

本文主要介紹了C++編寫的WebSocket服務端客戶端實現示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

使用過標準的libwebsockets服務端庫測試過,主要是短小精悍,相對于libwebsockets不需要依賴zlib和openssl 以及其他庫,直接make就可以使用了,linux跟windows都可以使用。

測試用例:

?
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
#include "easywsclient.hpp"
#include <assert.h>
#include <stdio.h>
#include <string>
 
using easywsclient::WebSocket;
static WebSocket::pointer ws = NULL;
 
void handle_message(const std::string & message)
{
    printf(">>> %s\n", message.c_str());
    if (message == "world") { ws->close(); }
}
 
int main()
{
    ws = WebSocket::from_url("ws://localhost:8126/foo");
    assert(ws);//判斷ws對象是否為空null
    ws->send("goodbye");
    ws->send("hello");
    //如果你需要多線程,可以在一個thread 維護該ws的連接重連機制
    while (ws->getReadyState() != WebSocket::CLOSED) //判斷ws是否正常連接
    {
      ws->poll();//這個必須要調用,否則不能發送,發送跟接收都是異步的,都是在這個poll函數里監測處理的
      ws->dispatch(handle_message);
    }
    delete ws;
    return 0;
}
?
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
//線程thread  維護重連連接
void run()
{
    bool conn = FLASE;
    ws = WebSocket::from_url("ws://localhost:8126/foo");
   
    //如果你需要多線程,可以在一個thread 維護該ws的連接重連機制
    while (1) //判斷ws是否正常連接
    {
      if(ws != NULL)
      {
          ws->poll(0);//這個必須要調用,否則不能發送,發送跟接收都是異步的,都是在這個poll函數里監測處    理的
          ws->dispatch(handle_message);
          if(ws->getReadyState() == WebSocket::CLOSED) 
          {
             //ws連接斷開 重連
             delete ws;
             ws = NULL;
             ws = WebSocket::from_url("ws://localhost:8126/foo");
          }
          else if(wss->getReadyState()== WebSocket::OPEN)
          {
             //ws連接ok
             //    ws->send("goodbye");
             ws->send("hello");
          }
          
      }
      else
      {
        ws = WebSocket::from_url("ws://localhost:8126/foo");
        sleep(1);
      }
      usleep(100);
    }
    if(ws!=NULL)
    delete ws;
}

有細心的朋友發現在發送中文GBK 的時候與服務端會斷開

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//GBK -> UTF-8
//遇到發送的字符串里有中文的話需要send 前進行轉換一下,
//這個是網友提供的在windows下的轉換函數
std::string Server_Stream::GBKToUTF8(const std::string& strGBK)
{
 std::string strOutUTF8 = "";
 WCHAR * str1;
 int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
 str1 = new WCHAR[n];
 MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
 n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
 char * str2 = new char[n];
 WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
 strOutUTF8 = str2;
 delete[]str1;
 str1 = NULL;
 delete[]str2;
 str2 = NULL;
 return strOutUTF8;
}

下面是C++實現的WebSocket客戶端,寫好后這里記一下,免得以后忘記。

本示例共有三個文件組成,依賴Websocket++第三方庫

其中main.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
#include <iostream>
#include <string>
#include <sstream>
 
#include "websocket_endpoint.h"
 
int main(int argc, char **argv)
{
 bool done = false;
 std::string input;
 kagula::websocket_endpoint endpoint;
 
 endpoint.connect("ws://localhost:9002");
 
 while (!done) {
  std::cout << "Enter Command: ";
  std::getline(std::cin, input);
 
  if (input == "quit") {
   done = true;
  }
  else if (input.substr(0, 4) == "send") {
   std::stringstream ss(input);
 
   std::string cmd;
   std::string message;
 
   ss >> cmd;
   std::getline(ss, message);
 
   endpoint.send(message);
  }
  else if (input.substr(0, 4) == "show") {
   endpoint.show();
  }
  else {
   std::cout << "> Unrecognized Command" << std::endl;
  }
 }
 
 endpoint.close();
 
 return 0;
}

其它兩個文件是封裝

websocket_endpoint.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
30
31
32
#ifndef _WEBSOCKET_ENDPOINT_
#define _WEBSOCKET_ENDPOINT_
 
#include <string>
 
/*
Title: Web Socket Client
Author: kagula
Date: 2016-11-21
Dependencies: Websocket++、Boost::ASIO
Test Environment: VS2013 Update5, WebSocket++ 0.70, Boost 1.61
Description:
[1]Support connect a web socket server.
[2]If server is crash, client will not follow crash.
*/
 
namespace kagula
{
 class websocket_endpoint {
 public:
  websocket_endpoint();
  ~websocket_endpoint();
 
  int connect(std::string const & uri);
  void close();
 
  void send(std::string message);
  void show();
 };
}
 
#endif

websocket_endpoint.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
 
#include <websocketpp/common/thread.hpp>
#include <websocketpp/common/memory.hpp>
 
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include <sstream>
 
#include "websocket_endpoint.h"
 
typedef websocketpp::client<websocketpp::config::asio_client> ws_client;
 
namespace kagula
{
 
 class connection_metadata {
 public:
  typedef websocketpp::lib::shared_ptr<connection_metadata> ptr;
 
  connection_metadata(websocketpp::connection_hdl hdl, std::string uri)
   : m_hdl(hdl)
   , m_status("Connecting")
   , m_uri(uri)
   , m_server("N/A")
  {}
 
  void on_open(ws_client *client, websocketpp::connection_hdl hdl) {
   m_status = "Open";
 
   ws_client::connection_ptr con = client->get_con_from_hdl(hdl);
   m_server = con->get_response_header("Server");
  }
 
  // if connection failed, the function will be invoke.
  void on_fail(ws_client *client, websocketpp::connection_hdl hdl) {
   m_status = "Failed";
 
   ws_client::connection_ptr con = client->get_con_from_hdl(hdl);
   m_server = con->get_response_header("Server");
   m_error_reason = con->get_ec().message();
  }
 
  void on_close(ws_client *client, websocketpp::connection_hdl hdl) {
   m_status = "Closed";
   ws_client::connection_ptr con = client->get_con_from_hdl(hdl);
   std::stringstream s;
   s << "close code: " << con->get_remote_close_code() << " ("
    << websocketpp::close::status::get_string(con->get_remote_close_code())
    << "), close reason: " << con->get_remote_close_reason();
   m_error_reason = s.str();
  }
 
  void on_message(websocketpp::connection_hdl, ws_client::message_ptr msg) {
   if (msg->get_opcode() == websocketpp::frame::opcode::text) {
    m_messages.push_back("<< " + msg->get_payload());
   }
   else {
    m_messages.push_back("<< " + websocketpp::utility::to_hex(msg->get_payload()));
   }
  }
 
  websocketpp::connection_hdl get_hdl() const {
   return m_hdl;
  }
 
  std::string get_status() const {
   return m_status;
  }
 
  std::string get_uri() const {
   return m_uri;
  }
 
  void record_sent_message(std::string message) {
   m_messages.push_back(">> " + message);
  }
 
  friend std::ostream & operator<< (std::ostream & out, connection_metadata const & data);
 private:
  websocketpp::connection_hdl m_hdl;
  std::string m_status;
  std::string m_uri;
  std::string m_server;
  std::string m_error_reason;
  std::vector<std::string> m_messages;
 };
 
 std::ostream & operator<< (std::ostream & out, connection_metadata const & data) {
  out << "> URI: " << data.m_uri << "\n"
   << "> Status: " << data.m_status << "\n"
   << "> Remote Server: " << (data.m_server.empty() ? "None Specified" : data.m_server) << "\n"
   << "> Error/close reason: " << (data.m_error_reason.empty() ? "N/A" : data.m_error_reason) << "\n";
  out << "> Messages Processed: (" << data.m_messages.size() << ") \n";
 
  std::vector<std::string>::const_iterator it;
  for (it = data.m_messages.begin(); it != data.m_messages.end(); ++it) {
   out << *it << "\n";
  }
 
  return out;
 }
 
 ws_client g_wsEndPoint;
 connection_metadata::ptr g_wsClientConnection;
 
 websocketpp::lib::shared_ptr<websocketpp::lib::thread> g_threadWS;
 
 websocket_endpoint::websocket_endpoint(){
   g_wsEndPoint.clear_access_channels(websocketpp::log::alevel::all);
   g_wsEndPoint.clear_error_channels(websocketpp::log::elevel::all);
 
   g_wsEndPoint.init_asio();
   g_wsEndPoint.start_perpetual();
 
   g_threadWS = websocketpp::lib::make_shared<websocketpp::lib::thread>(&ws_client::run, &g_wsEndPoint);
 }
 
 websocket_endpoint::~websocket_endpoint() {
  g_wsEndPoint.stop_perpetual();
  
  if (g_wsClientConnection->get_status() == "Open") {
   // Only close open connections
   websocketpp::lib::error_code ec;
   g_wsEndPoint.close(g_wsClientConnection->get_hdl(), websocketpp::close::status::going_away, "", ec);
   if (ec) {
    std::cout << "> Error closing ws connection " << g_wsClientConnection->get_uri() << " :" << ec.message() << std::endl;
   }
  }
 
  g_threadWS->join();
 }
 
 int websocket_endpoint::connect(std::string const & uri) {
  websocketpp::lib::error_code ec;
 
  ws_client::connection_ptr pConnection = g_wsEndPoint.get_connection(uri, ec);
 
  if (ec) {
   std::cout << "> Connect initialization error: " << ec.message() << std::endl;
   return -1;
  }
 
  g_wsClientConnection = websocketpp::lib::make_shared<connection_metadata>(pConnection->get_handle(), uri);
 
  pConnection->set_open_handler(websocketpp::lib::bind(
   &connection_metadata::on_open,
   g_wsClientConnection,
   &g_wsEndPoint,
   websocketpp::lib::placeholders::_1
   ));
  pConnection->set_fail_handler(websocketpp::lib::bind(
   &connection_metadata::on_fail,
   g_wsClientConnection,
   &g_wsEndPoint,
   websocketpp::lib::placeholders::_1
   ));
  pConnection->set_close_handler(websocketpp::lib::bind(
   &connection_metadata::on_close,
   g_wsClientConnection,
   &g_wsEndPoint,
   websocketpp::lib::placeholders::_1
   ));
  pConnection->set_message_handler(websocketpp::lib::bind(
   &connection_metadata::on_message,
   g_wsClientConnection,
   websocketpp::lib::placeholders::_1,
   websocketpp::lib::placeholders::_2
   ));
 
  g_wsEndPoint.connect(pConnection);
 
  return 0;
 }
 
 void close(websocketpp::close::status::value code, std::string reason) {
  websocketpp::lib::error_code ec;
 
  g_wsEndPoint.close(g_wsClientConnection->get_hdl(), code, reason, ec);
  if (ec) {
   std::cout << "> Error initiating close: " << ec.message() << std::endl;
  }
 }
 
 void websocket_endpoint::close()
 {
  if (g_wsClientConnection->get_status()=="Open")
  {
   int close_code = websocketpp::close::status::normal;
   kagula::close(close_code, "");
  }
 }
 
 void websocket_endpoint::send(std::string message) {
  websocketpp::lib::error_code ec;
 
  g_wsEndPoint.send(g_wsClientConnection->get_hdl(), message, websocketpp::frame::opcode::text, ec);
  if (ec) {
   std::cout << "> Error sending message: " << ec.message() << std::endl;
   return;
  }
 
  g_wsClientConnection->record_sent_message(message);
 }
 
 void websocket_endpoint::show()
 {
  std::cout << * g_wsClientConnection << std::endl;
 }
}

到此這篇關于C++編寫的WebSocket客戶端實現示例代碼的文章就介紹到這了,更多相關C++ WebSocket客戶端內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://blog.csdn.net/lee353086/article/details/53260513

延伸 · 閱讀

精彩推薦
  • C/C++C/C++經典實例之模擬計算器示例代碼

    C/C++經典實例之模擬計算器示例代碼

    最近在看到的一個需求,本以為比較簡單,但花了不少時間,所以下面這篇文章主要給大家介紹了關于C/C++經典實例之模擬計算器的相關資料,文中通過示...

    jia150610152021-06-07
  • C/C++學習C++編程的必備軟件

    學習C++編程的必備軟件

    本文給大家分享的是作者在學習使用C++進行編程的時候所用到的一些常用的軟件,這里推薦給大家...

    謝恩銘10102021-05-08
  • C/C++C語言中炫酷的文件操作實例詳解

    C語言中炫酷的文件操作實例詳解

    內存中的數據都是暫時的,當程序結束時,它們都將丟失,為了永久性的保存大量的數據,C語言提供了對文件的操作,這篇文章主要給大家介紹了關于C語言中文件...

    針眼_6702022-01-24
  • C/C++c++ 單線程實現同時監聽多個端口

    c++ 單線程實現同時監聽多個端口

    這篇文章主要介紹了c++ 單線程實現同時監聽多個端口的方法,幫助大家更好的理解和學習使用c++,感興趣的朋友可以了解下...

    源之緣11542021-10-27
  • C/C++詳解c語言中的 strcpy和strncpy字符串函數使用

    詳解c語言中的 strcpy和strncpy字符串函數使用

    strcpy 和strcnpy函數是字符串復制函數。接下來通過本文給大家介紹c語言中的strcpy和strncpy字符串函數使用,感興趣的朋友跟隨小編要求看看吧...

    spring-go5642021-07-02
  • C/C++深入理解goto語句的替代實現方式分析

    深入理解goto語句的替代實現方式分析

    本篇文章是對goto語句的替代實現方式進行了詳細的分析介紹,需要的朋友參考下...

    C語言教程網7342020-12-03
  • C/C++C語言實現電腦關機程序

    C語言實現電腦關機程序

    這篇文章主要為大家詳細介紹了C語言實現電腦關機程序,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    xiaocaidayong8482021-08-20
  • C/C++C++之重載 重定義與重寫用法詳解

    C++之重載 重定義與重寫用法詳解

    這篇文章主要介紹了C++之重載 重定義與重寫用法詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下...

    青山的青6062022-01-04
主站蜘蛛池模板: 综合久久久久 | 青草青草久热精品视频在线观看 | 另类五月 | av在线电影网 | 国产aaaaav久久久一区二区 | 久久国产精品久久久久久电车 | av不卡在线播放 | 精品天堂 | 色乱码一区二区三区网站 | 九九热1 | 欧美日韩一区二区三区在线电影 | 中文字幕一区二区三区乱码在线 | 中文字幕精品一区二区三区精品 | 中文视频在线 | 午夜视频在线观看免费视频 | 免费一级特黄3大片视频 | 国产黄色免费网站 | 日韩电影网站 | 久久久久久久国产精品 | 亚洲国产精品久久人人爱 | 在线免费av观看 | 国产日韩欧美在线观看 | 香蕉视频禁止18 | 亚洲精品第一区在线观看 | 久久精品国产一区二区三区不卡 | 精品电影 | 国产一区视频在线看 | 久久久天堂 | 欧美综合一区 | 天堂成人av | 国产成人精品免费视频 | 99热少妇 | 国产精品视频久久久 | 亚洲成人免费在线播放 | 午夜成人免费视频 | 在线精品一区二区 | 欧美中文字幕一区二区三区亚洲 | 91一区 | 91视频久久 | 丝袜久久 | 日本一区二区在线看 |