无法将数据发送到 libwebsocket 服务器 [英] Unable to send data to libwebsocket server

查看:65
本文介绍了无法将数据发送到 libwebsocket 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 X-Plane 编写一个小插件,以便使用 libwebsocket 创建一个简单的 websocket 服务器.我可以从 Google Chrome 连接到 websocket,但是,当我向服务器发送数据时,X-Plane 立即崩溃.

I'm trying to write a small plugin for X-Plane, to create a simple websocket server with libwebsocket. I'm able to connect to the websocket from Google Chrome, however, when I send data to the server, X-Plane immediately crashes.

我很确定 以下代码导致问题:

unsigned char *buf = (unsigned char*) malloc(LWS_SEND_BUFFER_PRE_PADDING + 13 + LWS_SEND_BUFFER_POST_PADDING);
buf = (unsigned char*) "Hello World!";
libwebsocket_write(wsi, buf, len, LWS_WRITE_TEXT);
free(buf);

我根本不是 C 程序员/专家,但上面的内容似乎有问题吗?

I'm not a C programmer / specialist at all, but does the above seem to have a problem at all?

我已经在 Gist 上发布了完整的源代码:https://gist.github.com/josefvanniekerk/868432986f2f963a5583

I've posted the full source on Gist: https://gist.github.com/josefvanniekerk/868432986f2f963a5583

推荐答案

对于任何理智的界面,@iharob 都是正确的 - 明确他/她你对字符串赋值的误解是正确的.

With any sane interface, @iharob would be right - to be clear he/she is right about you misunderstanding string assignment.

然而,libwebsockets 有点特别".您需要将字符串复制到 malloc() 的数组 LWS_SEND_BUFFER_PRE_PADDING 字节中.libwebsockets 然后覆盖前面的字节.

However, libwebsockets is a bit 'special'. You need to copy the string into the malloc()'d array LWS_SEND_BUFFER_PRE_PADDING bytes in. libwebsockets then overwrites the preceding bytes.

所以你想要类似的东西(假设你没有尝试在字符串上发送终止零):

So you want something like (assuming you are not trying to send the terminating zero on the string):

char *text = "Hello World!";
int len = strlen (text);
unsigned char *buf = malloc(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING);
/* copy string but not terminating NUL */
memcpy (buf + LWS_SEND_BUFFER_PRE_PADDING, text, len );
libwebsocket_write(wsi, buf + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
free(buf);

如果您还想发送 NUL:

char *text = "Hello World!";
int len = strlen (text) + 1;
unsigned char *buf = malloc(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING);
/* copy string including terminating NUL */
memcpy (buf + LWS_SEND_BUFFER_PRE_PADDING, text, len );
libwebsocket_write(wsi, buf + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
free(buf);

这篇关于无法将数据发送到 libwebsocket 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆