Closed hopbkpro92 closed 4 years ago
@hopbkpro92 Hello
You need install this options to server and client
The example (rename awaitId to testRequestId):
const WebSocketAwait = require('ws-await');
const options = {
awaitTimeout: 10000,
leaveAwaitId: false,
packMessage: data => JSON.stringify(data),
unpackMessage: data => JSON.parse(data),
generateAwaitId: () => `_${Math.random()
.toString(36)
.substr(2, 10)}`,
attachAwaitId: (data, id) => Object.assign({testRequestId: id}, data),
extractAwaitId: data => data &&
Object.prototype.hasOwnProperty.call(data, 'testRequestId') && data.testRequestId,
deleteAwaitId: data => delete data.testRequestId,
};
const wss = new WebSocketAwait.Server({
port: 6060,
...options
},);
wss.on('connection', ws => {
ws.on('messageAwait', (msg, id) => {
console.log(`Server get messageAwait <<< ${msg.foo} and ${id}`);
ws.resAwait({
bar: 'foo'
}, id);
});
});
const ws = new WebSocketAwait('ws://localhost:6060', options);
ws.on('open', async () => {
const waiting = await ws.sendAwait({
foo: 'bar'
});
console.log(`Client get waiting <<< ${waiting.bar}`);
});
Output:
Server get messageAwait <<< bar and _vxlb0enri2
Client get waiting <<< foo
Please check your code, thanks
@stas-ut21 Thanks you very much for your response.
My server is created by C++ using mongoosee. I updated server to response message which has filed "testRequestId" but no response is received at client side (extractAwaitId function is not called).
I think server must be written in Javascript. Is it right ? Please help me confirm it. Many thanks.
@hopbkpro92
No, not necessarily But most importantly you must send a response to the client in the correct format
Here is an example with a raw messages(this is from the example above)
{"testRequestId":"_bqzfv8j0da","foo":"bar"}
Server get messageAwait <<< bar and _bqzfv8j0da
{"testRequestId":"_bqzfv8j0da","bar":"foo"}
Client get waiting <<< foo
@stas-ut21 Thank you for you response
It's is error in my server. Format is not correct. I fixed and result is OK.
Thank you very much
@hopbkpro92 Good job, great =)
In client side, I update "awaitId" to other name ("testRequestId"). For example:
In server side, I also rename "awaitId" to "testRequestId" but when I send request to server using "sendAwait()", no response is received (extractAwaitId function is not called). When I use "awaitId" name, messages are received normally.
I think "awaitId" can not be rename. Is it right ?