Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
WebSocket needs browser refresh to update list

My project works as intended except that I have to refresh the browser every time my keyword list sends something to it to display. I assume it's my inexperience with Expressjs and not creating the route correctly within my websocket? Any help would be appreciated.

Browser

let socket = new WebSocket("ws://localhost:3000");

socket.addEventListener('open', function (event) { 
  console.log('Connected to WS server')
  socket.send('Hello Server!'); 
}); 

socket.addEventListener('message', function (e) {
  const keywordsList = JSON.parse(e.data);
  console.log("Received: '" + e.data + "'");
  document.getElementById("keywordsList").innerHTML = e.data;
}); 

socket.onclose = function(code, reason) {
  console.log(code, reason, 'disconnected');
}

socket.onerror = error => {
  console.error('failed to connect', error);
}; 

Server

const ws = require('ws');
const express = require('express');
const keywordsList = require('./app');

const app = express();
const port = 3000;

const wsServer = new ws.Server({ noServer: true });
wsServer.on('connection', function connection(socket) {
  socket.send(JSON.stringify(keywordsList));
  socket.on('message', message => console.log(message));
});

// `server` is a vanilla Node.js HTTP server, so use
// the same ws upgrade process described here:
// https://www.npmjs.com/package/ws#multiple-servers-sharing-a-single-https-server
const server = app.listen(3000);
server.on('upgrade', (request, socket, head) => {
  wsServer.handleUpgrade(request, socket, head, socket => {
    wsServer.emit('connection', socket, request);
  });
}); 
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In answer to "How to Send and/or Stream array data that is being continually updated to a client" as arrived at in comment.

A possible solution using WebSockets may be to

  1. Create an interface on the server for array updates (if you haven't already) that isolates the array object from arbitrary outside modification and supports a callback when updates are made.

  2. Determine the latency allowed for multiple updates to occur without being pushed. The latency should allow reasonable time for previous network traffic to complete without overloading bandwidth unnecessarily.

  3. When an array update occurs, start a timer if not already running for the latency period .

  4. On timer expiry JSON.stringify the array (to take a snapshot), clear the timer running status, and message the client with the JSON text.

A slightly more complicated method to avoid delaying all push operations would be to immediately push single updates unless they occur within a guard period after the most recent push operation. A timer could then push modifications made during the guard period at the end of the guard period.


Broadcasting

The WebSockets API does not directly support broadcasting the same data to multiple clients. Refer to Server Broadcast in ws documentation for an example of sending data to all connected clients using a forEach loop.


Client side listener

In the client-side message listener

document.getElementById("keywordsList").innerHTML = e.data;

would be better as

document.getElementById("keywordsList").textContent = keywordList;

to both present keywords after decoding from JSON and prevent them ever being treated as HTML.

about 4 years ago · Juan Pablo Isaza Report

0

So I finally figured out what I wanted to accomplish. It sounds straight forward after I learned enough and thought about how to structure the back end of my project.

If you have two websockets running and one needs information from the other, you cannot run them side by side. You need to have one encapsulate the other and then call the websocket INSIDE of the other websocket. This can easily cause problems down the road for other projects since now you have one websocket that won't fire until the other is run but for my project it makes perfect sense since it is locally run and needs all the parts working 100 percent in order to be effective. It took me a long time to understand how to structure the code as such.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!