javascript - WebSocket binary transmission returns more data than server sent -
i have issue receiving binary data on websocket number of bytes received browser (in form of arraybuffer, in javascript) higher server sent, though chrome or firefox report correctly how many bytes transmitted on wire.
the server side node js, , have used 3 different packages (ws, nodejs-websocket , websocket) , behave same. it's issue in javascript running in browser.
my code on client side looks this:
1: var socket = new websocket(url); 2: socket.binarytype = 'arraybuffer'; 3: socket.onmessage = function(event) { 4: var buffer = new uint8array(event.data); 5: // consume buffer 6: }
the problem if examine length of "buffer" (after line 4), it's higher data sent server.
for example, if server sends binary content, 8 bytes:
0xa1 0xb2 0xc3 0xd4 0xa1 0xb2 0xc3 0xd4
on client side, see:
0xc2 0xa1 0xc2 0xb2 0xc3 0x83 0xc3 0x94 0xc2 0xa1 0xc2 0xb2 0xc3 0x83 0xc3 0x94
update: after further examination, believe has word alignment of data in memory. example, if send following data: 0x7c 0x7d 0x7e 0x7f, it's received correctly. consume higher bits, 0x81, 0xc2 gets added data.
i can't believe have deal this! perhaps doing wrong, did @ other frameworks transferring binary data on websocket and, in fact, "unpacking" real data out of word-aligned array buffer.
update 2: completion purposes, what's happening on server, using nodejs package websocket, conn web socket connection obtained websocket package.
function sendbinary(conn, filename) { var size = 4096; var inputstream = fs.createreadstream( filename, { 'flags': 'r', 'encoding': 'binary', 'buffersize': size }); inputstream.on('data', function(data) { conn.sendbytes(new buffer(data)); }); }
thank taking time read this. appreciated.
when print or write stream, make sure use original buffer stream, not string. in case may outprint string instead of buffer. buf.tostring() use encode utf-8 default, , chinese character in utf-8 takes 3bytes, , unexpected bytes.
by way, 0xa1 chinese character starts
please use iconv-lite convert string buffer if need
or refer this post combine binary buffer in server side
Comments
Post a Comment