I am wondering what websocket events exist So far I have only been using the ws.on('message')
event, but I would like to use an event that is triggered when the connection is established and closed. I tried adding ws.on('connection')
, but that didn't get triggered.
My code:
app.ws('/', function (ws, req) {
ws.on('message', function (textChunk) {
//do stuff
}
});
});
Do I need some client side programming to do this?
I tried adding this, but it didn't trigger when I connected from my client.
ws.on('request', function () {
console.log("request");
});
Creating a websocket server import express from "express"; import startup from "./lib/startup"; import api from "./api/index"; import middleware from "./middleware/index"; import logger from "./lib/logger"; import websockets from './websockets'; startup() . then(() => { const app = express(); const port = process. env.
The only way to know the client received the webSocket message for sure is to have the client send your own custom message back to the server to indicate you received it and for you to wait for that message on the server. That's the ONLY end-to-end test that is guaranteed.
Web Socket is a protocol that provides full-duplex(multiway) communication i.e allows communication in both directions simultaneously. It is a modern web technology in which there is a continuous connection between the user's browser(client) and the server.
The function provided to app.ws
is the one executed when a new websocket is opened. So use it this way:
app.ws('/', function (ws, req) {
console.log("New connection has opened!");
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('message', function (message) {
console.log('Message received: '+message);
});
});
After looking at the source code for express-ws
it looks like you can do the following.
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
// get the WebsocketServer instance with getWss()
// https://github.com/HenningM/express-ws/blob/5b5cf93bb378a0e6dbe6ab33313bb442b0c25868/index.js#L72-L74
expressWs.getWss().on('connection', function(ws) {
console.log('connection open');
});
// ... express middleware
// ... websocket middle ware
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
});
app.listen(3000);
There are the following:
close
error
message
open
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Attributes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With