Reputation: 12395
I notice WebSocket extends EventTarget and EventTarget.dispatchEvent()
"sends an Event to the object". But it is not clear from that MDN document who the object is.
I had thought maybe that object was the receiver on the WebSocket server side and dispatchEvent()
is another way to send a message to the ws server like WebSocket.send()
So I did the following test in the browser console to see if that is the case(using https://github.com/websockets/ws for ws server).
const ws = new WebSocket('ws://localhost:3000');
//instead of using ws.send('hello world'); I use dispatchEvent here
//as I want to know what dispatchEvent does,
//e.g can it send my message to ws server like send() ?
ws.addEventListener('open', (evt) => {
let event = new MessageEvent('message', {
data: "hello world",
lastEventId: '101'
});
ws.dispatchEvent(event);
});
ws.addEventListener('message', (event) => {
console.log('Message from server ', event.data);
});
//Here is my server codes
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 3000 })
wss.on('connection', function connection(ws) {
console.log(`A ${ws.url}} connects`)
ws.on('message', (evt) => {
console.log(`on message:received: ${evt}`)
ws.send('test callback')
})
})
But as it turns out the console immediately prints out "Message from server hello world" while ws server didn't get that event.
So what is the use of dispatchEvent()
in WebSocket ?
Upvotes: 2
Views: 1014
Reputation: 8087
The EventTarget interface is implemented by objects that can receive events, and is an interface that your ws
(WebSocket) variable will implement to receive communication events from the low-level browser implementation of that network socket (such as when it successfully opens, and when a message is received).
However, you're not supposed to call it yourself. What you're doing is manually feeding it an event, and causing the WebSocket to behave as if it was an real event that has arrived from the remote server.
Therefore, your code is only useful in testing scenarios where you are emulating a server response.
Upvotes: 3