我用的是c++,调用官网的c++ libwebsockets:https://libwebsockets.org/
默认是读取顺序从最旧的数据读到最新的数据,为了避免数据量太大时阻塞响应慢,想每次直接读取最新的数据。网上只看到一篇好像是GO如何实现:
wss数据推送速度很快,Go的底层会把所有的数据缓存在队列中,等程序调用read时,再依次返回。read()如果不加参数,会返回最旧的数据,没数据时阻塞到返回。如果想要最新数据,可以用client.read(-2)立即返回最新数据,但再没数据时回返回null,需要判断再引用:
function main() {
var client = Dial("ws://省略详细网站");
while (true) {
var msg = client.read()
//省略其他处理data数据
}
}
附我目前的代码:
轮询代码:
while( true)
{
try {
lws_service( context, 500 );
}
}
回调函数代码:
int event_cb( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len )
{
switch( reason )
{
case LWS_CALLBACK_CLIENT_RECEIVE:
/* Handle incomming messages here. */
try {
string str_result = string( (char*)in );
Json::Reader reader;
Json::Value json_result;
reader.parse( str_result , json_result );
if ( handles.find( wsi ) != handles.end() )
{
handles[wsi]( json_result );
}
}
break;
//省略其他代码
}
}