c - Libwesockets:如何从 websocket 正确读取文本(json)数据?
问题描述
我有这样的 websocket 实现,它以前可以工作,但现在不行,因为我升级了库版本。
int Handle(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
switch( reason ) {
case LWS_CALLBACK_CLOSED: {
lwsl_notice("Client Disconnected\n");
break;
}
case LWS_CALLBACK_ESTABLISHED: {
lwsl_notice("Client Connected\n");
break;
}
case LWS_CALLBACK_RECEIVE: {
lwsl_notice("Message: %s\n", in);
break;
}
default:
break;
}
return 0;
}
static struct lws_protocols protocols[] =
{
{
"server",
Handle,
sizeof(struct Session),
LWS_MESSAGE_CHUNK_SIZE,
},
{ NULL, NULL, 0, 0 }
};
int Start() {
struct lws_context_creation_info info;
memset( &info, 0, sizeof(info) );
info.port = 3018;
info.protocols = protocols;
info.gid = -1;
info.uid = -1;
struct lws_context *context = lws_create_context( &info );
while( 1 ) {
lws_service( context, 1000000 );
}
lws_context_destroy( context );
}
问题是数据最后会带有一些噪音。
如果我从一端发送,{}
我会在另一端接收{}/S4T1u3F2O1AA82K7Kg=
。因此*in
在实际消息字符串之后包含此噪声。我怎样才能正确接收数据?
我尝试了不同的示例,但它们看起来过于复杂。
解决方案
我设法将适量的数据复制到字符串中。我的解决方案:
char data[len];
memcpy(data, in, len);
data[len] = '\0';
推荐阅读
- dns - 如何从别名记录集切换到 Route 53 中的 CName 记录集,避免任何停机?
- javascript - React Native 中的状态异步问题
- java - 为什么我的程序无法在我的材质对话框方法中解析符号“Builder”
- java - 为什么在应用程序的构造函数中调用 android.content.Context.getApplicationContext() 时会出现 NPE?
- c# - 在脚本中更改 Cinemachine 的相机距离
- python - 如何让 Python 从网络上转储文本行?
- flutter - Flutter - 动画完成后滚动
- angular - ASPWebApi 对预检请求的响应未通过访问控制检查
- python-3.x - 我尝试使用 chr python 3 时遇到问题
- google-maps - 在 Flutter 上启动缓慢的 Google 地图导航