Skip to content

Commit

Permalink
Add an option to send bytes with ws
Browse files Browse the repository at this point in the history
  • Loading branch information
YoniGang committed Feb 18, 2023
1 parent 5f7ed31 commit 20208e1
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 6 deletions.
13 changes: 12 additions & 1 deletion examples/websockets/my-functions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = { createRandomScore };
module.exports = { createRandomScore, sendStream };

function createRandomScore(userContext, events, done) {
const data = {
Expand All @@ -11,3 +11,14 @@ function createRandomScore(userContext, events, done) {

return done();
}

function sendStream(userContext, events, done) {
const fs = require('fs');
const path = '/path/to/your/wavfile.wav';

userContext.vars.byteData = fs.readFile(path, (err, data) => {
// put it on byteData variable to not overide the "data" variable
userContext.vars.byteData = data;
return done();
});
}
3 changes: 3 additions & 0 deletions examples/websockets/websockets.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ scenarios:
flow:
- function: "createRandomScore"
- send: "{{ data }}"
- function: "sendStream"
- sendBytes: "{{ byteData }}"
- sendBytes: "ABC" # It will turn the string into bytes automatically
26 changes: 21 additions & 5 deletions packages/core/lib/engine_ws.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,25 @@ WSEngine.prototype.step = function (requestSpec, ee) {
};
}

const get_string_payload = (payload) => {
if (typeof payload === 'object') {
return JSON.stringify(payload);
}

return _.toString(payload);
}

const get_bytes_payload = (payload) => {
if (typeof payload === 'string') {
let utf8Encode = new TextEncoder()
return utf8Encode.encode(payload).buffer
}

return payload
}

const f = function (context, callback) {
const params = requestSpec.wait || requestSpec.send;
const params = requestSpec.wait || requestSpec.send || requestSpec.sendBytes;

// match exists on a string, so check match is not a prototype
let captureOrMatch = _.has(params, 'capture') || _.has(params, 'match');
Expand All @@ -192,12 +209,11 @@ WSEngine.prototype.step = function (requestSpec, ee) {

if (payload !== undefined) {
payload = template(payload, context);
if (typeof payload === 'object') {
payload = JSON.stringify(payload);
if (requestSpec.sendBytes) {
payload = get_bytes_payload(payload)
} else {
payload = _.toString(payload);
payload = get_string_payload(payload)
}

ee.emit('counter', 'websocket.messages_sent', 1);
ee.emit('rate', 'websocket.send_rate');
debug('WS send: %s', payload);
Expand Down

0 comments on commit 20208e1

Please sign in to comment.