#inclu..._websocket from_url">
赞
踩
源代码见 websocket client
使用过标准的libwebsockets服务端库测试过,主要是短小精悍,相对于libwebsockets不需要依赖zlib和openssl 以及其他库,直接make就可以使用了,linux跟windows都可以使用。
测试用例:
- #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;
- }

- //线程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 -> 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;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。