I'm integrating websockets with express on the backend and using browser's native websocket api on the client side. I have so far been able to send and receive message from the client to server and server back to client. But all this happens with a page refresh only. Isn't websocket supposed to be real time? Lets say I make a change in the message on server file, then it has to immediately reflect in my browser's console. and lets say I make a change in the message in the script file on the client side, then it has to immediately show the changes on server's console.(Also I'm using nodemon to run the server so changes has to reflect pretty quickly). But right now, I see myself making a request to /
via page refresh and then server upgrading and then responding back with the message.
Please tell me if I'm missing something in the code or otherwise in the concept?
app.js
const express = require('express')
const app = express()
const path = require('path')
const WebSocketServer = require('websocket').server;
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, '/public')))
const port = 8080
app.get('/', (req, res) => {
res.render('index')
})
const server = app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
wsServer = new WebSocketServer({
httpServer: server
});
function originIsAllowed(origin) {
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log((new Date()) ' Connection from origin ' request.origin ' rejected.');
return;
}
var connection = request.accept(null, request.origin);
console.log((new Date()) ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' message.utf8Data);
connection.sendUTF("server says hi");
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' message.binaryData.length ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) ' Peer ' connection.remoteAddress ' disconnected.');
});
});
client.js:
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello to Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
CodePudding user response:
I am not sure if I understand the question, but if you want the client to send message to server, you have do it the same way as it is done in open listener:
socket.send('MESSAGE FOR SERVER')
or, if server should send something to client, then just
connection.send('MESSAGE FOR CLIENT')
.
Realtime communication with WebSocket means, the connection is created only once and the protocol is kept opened (Unlike REST API, where the connection is created with every request.)
The message must be sent actively either from server or client, there is nothing observing some message state and updating it on the other side.