thoov / mock-socket

Javascript mocking library for WebSockets and Socket.IO
MIT License
800 stars 119 forks source link

Binary messages? #6

Open dtracers opened 9 years ago

dtracers commented 9 years ago

I could not find anything about it supporting binary messages. Does this library support mocking of binary messages?

thoov commented 9 years ago

@dtracers right now there is no native support for binary messages but it will be on of the next things I work on adding.

cades commented 9 years ago

+1

thoov commented 9 years ago

@cades or @dtracers do you have any examples I could use as a test case? If so I will be able to add support quickly

dtracers commented 9 years ago

I use protobuf.js.

So a good example test might be sending a hello world protobuf file via binary.

I don't think I'll be able to come up with one until this weekend. And maybe not even then. On Jun 5, 2015 11:01 AM, "Travis Hoover" notifications@github.com wrote:

@cades https://github.com/cades or @dtracers https://github.com/dtracers do you have any examples I could use as a test case? If so I will be able to add support quickly

— Reply to this email directly or view it on GitHub https://github.com/thoov/mock-socket/issues/6#issuecomment-109363649.

nomve commented 9 years ago

I don't know if something changed in the meantime, but this works:

    var binaryDataBuffer = new ArrayBuffer(1),
        binaryDataArray = new Uint8Array(binaryDataBuffer);

    clientInstance.onmessage = function(event) {
        var data = new Uint8Array(event.data);
        QUnit.equal( data[0], 1, "didn't receive the right data" );
    };

    binaryDataArray[0] = 1;
    serverInstance.send(binaryDataBuffer);
jocull commented 4 years ago

It seems to work as long as you consistently use ArrayBuffer and related views on both sides.

If you send a Buffer type from Node something seems to get crossed and an empty ArrayBuffer appears on the other side.

server.on('connection', socket => {
  socket.on('message', (msg) => {
    const encodedAsNodeBuffer = myBufferGenerator();
    const newBuffer = new ArrayBuffer(encodedAsNodeBuffer.byteLength);
    const newBufferView = new Uint8Array(newBuffer);
    newBufferView.set(encodedAsNodeBuffer, 0);
    socket.send(newBuffer);
  }
}

The protobufjs code generator seems to use Buffer on the Node side, so something to be aware of if you are using that.