#inclu..._websocket from_url">
当前位置:   article > 正文

C/C++ 实现的websocket客户端_websocket from_url

websocket from_url

源代码见 websocket client

使用过标准的libwebsockets服务端库测试过,主要是短小精悍,相对于libwebsockets不需要依赖zlibopenssl 以及其他库,直接make就可以使用了,linux跟windows都可以使用。

测试用例:

  1. #include "easywsclient.hpp"
  2. #include <assert.h>
  3. #include <stdio.h>
  4. #include <string>
  5. using easywsclient::WebSocket;
  6. static WebSocket::pointer ws = NULL;
  7. void handle_message(const std::string & message)
  8. {
  9. printf(">>> %s\n", message.c_str());
  10. if (message == "world") { ws->close(); }
  11. }
  12. int main()
  13. {
  14. ws = WebSocket::from_url("ws://localhost:8126/foo");
  15. assert(ws);//判断ws对象是否为空null
  16. ws->send("goodbye");
  17. ws->send("hello");
  18. //如果你需要多线程,可以在一个thread 维护该ws的连接重连机制
  19. while (ws->getReadyState() != WebSocket::CLOSED) //判断ws是否正常连接
  20. {
  21. ws->poll();//这个必须要调用,否则不能发送,发送跟接收都是异步的,都是在这个poll函数里监测处理的
  22. ws->dispatch(handle_message);
  23. }
  24. delete ws;
  25. return 0;
  26. }
  1. //线程thread 维护重连连接
  2. void run()
  3. {
  4. bool conn = FLASE;
  5. ws = WebSocket::from_url("ws://localhost:8126/foo");
  6. //如果你需要多线程,可以在一个thread 维护该ws的连接重连机制
  7. while (1) //判断ws是否正常连接
  8. {
  9. if(ws != NULL)
  10. {
  11. ws->poll(0);//这个必须要调用,否则不能发送,发送跟接收都是异步的,都是在这个poll函数里监测处 理的
  12. ws->dispatch(handle_message);
  13. if(ws->getReadyState() == WebSocket::CLOSED)
  14. {
  15. //ws连接断开 重连
  16. delete ws;
  17. ws = NULL;
  18. ws = WebSocket::from_url("ws://localhost:8126/foo");
  19. }
  20. else if(wss->getReadyState()== WebSocket::OPEN)
  21. {
  22. //ws连接ok
  23. // ws->send("goodbye");
  24. ws->send("hello");
  25. }
  26. }
  27. else
  28. {
  29. ws = WebSocket::from_url("ws://localhost:8126/foo");
  30. sleep(1);
  31. }
  32. usleep(100);
  33. }
  34. if(ws!=NULL)
  35. delete ws;
  36. }

有细心的朋友发现在发送中文GBK 的时候与服务端会断开

 

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

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/241822
推荐阅读
相关标签
  

闽ICP备14008679号