javascript - Send text and binary via websocket - Stack Overflow

Is there any way to send text and binary in one request via websocket? For example: file name (text) an

Is there any way to send text and binary in one request via websocket? For example: file name (text) and file content (binary)

I can send them as string like:

JSON.stringify({filename: "test.dat", filecontent: data});

But it is a lot slower than sending only file content as binary (arraybuffer).

Is there any way to send text and binary in one request via websocket? For example: file name (text) and file content (binary)

I can send them as string like:

JSON.stringify({filename: "test.dat", filecontent: data});

But it is a lot slower than sending only file content as binary (arraybuffer).

Share Improve this question asked Jun 24, 2016 at 22:01 potenterpotenter 551 silver badge9 bronze badges 3
  • Maybe you want to look at a different data interchange format that has native support for binary data, such as MsgPack. – mpen Commented Jun 24, 2016 at 22:05
  • @mpen - webSocket supports binary data. – jfriend00 Commented Jun 24, 2016 at 22:36
  • @jfriend00 Right.. I'm saying instead of using JSON.stringify use msgpack.encode. – mpen Commented Jun 24, 2016 at 23:21
Add a ment  | 

1 Answer 1

Reset to default 7

Remember that binary is just encoded data. This is less a JavaScript question and more an encoding question. Here's how I would do it.

Set aside 32 bits (representing one integer) at the beginning of your request to specify the bit length of test.dat. Then bine this with your two data sources. Your payload will look like this:

TEXT_LENGTH + TEST.DAT AS BINARY + FILECONTENT AS BINARY

Then get back the data as an array buffer. Use

textLengthBits = parseInt(arrBuffer.slice(0,32), 2);

To get the length of the text. Then slice again,

textBits = arrBuffer.slice(32, 32 + textLengthBits)

To get the text. The remaining bits are your file.

fileBits = arrBuffer.slice(32 + textLengthBits);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745112644a4611937.html

相关推荐

  • javascript - Send text and binary via websocket - Stack Overflow

    Is there any way to send text and binary in one request via websocket? For example: file name (text) an

    10小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信