Skip to content

Commit

Permalink
Handle binary WS message using a separate event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan Mirić committed Apr 1, 2021
1 parent b80813c commit e44fb6d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
7 changes: 5 additions & 2 deletions js/modules/k6/ws/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,11 @@ func (*WS) Connect(ctx context.Context, url string, args ...goja.Value) (*WSHTTP
Tags: socket.sampleTags,
Value: 1,
})
ab := rt.NewArrayBuffer(readData)
socket.handleEvent("message", rt.ToValue(string(readData)), rt.ToValue(&ab))
socket.handleEvent("message", rt.ToValue(string(readData)))
if _, ok := socket.eventHandlers["binaryMessage"]; ok {
ab := rt.NewArrayBuffer(readData)
socket.handleEvent("binaryMessage", rt.ToValue(&ab))
}

case readErr := <-readErrChan:
socket.handleEvent("error", rt.ToValue(readErr))
Expand Down
14 changes: 13 additions & 1 deletion js/modules/k6/ws/ws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,15 +382,21 @@ func TestSocketSendBinary(t *testing.T) {
assert.NoError(t, err)

_, err = rt.RunString(sr(`
var gotMsg = false, gotBinMsg = false;
var res = ws.connect('WSBIN_URL/ws-echo', function(socket){
var data = new Uint8Array([104, 101, 108, 108, 111]); // 'hello'
socket.on('open', function() {
socket.sendBinary(data.buffer);
})
socket.on('message', function (msg, msgBin){
socket.on('message', function(msg) {
gotMsg = true;
if (msg !== 'hello') {
throw new Error('received unexpected message: ' + msg);
}
});
socket.on('binaryMessage', function(msgBin) {
gotBinMsg = true;
let decText = String.fromCharCode.apply(null, new Uint8Array(msgBin));
decText = decodeURIComponent(escape(decText));
if (decText !== 'hello') {
Expand All @@ -399,6 +405,12 @@ func TestSocketSendBinary(t *testing.T) {
socket.close()
});
});
if (!gotMsg) {
throw new Error("the 'message' handler wasn't called")
}
if (!gotBinMsg) {
throw new Error("the 'binaryMessage' handler wasn't called")
}
`))
assert.NoError(t, err)
}
Expand Down

0 comments on commit e44fb6d

Please sign in to comment.