node.js – Node WebSocket server refusing connections from browser based clients

I’ve been experiencing problems getting browser clients to connect to my Node Websocket server. My browser-based clients are javascript files being served by HTTP a server running on ‘localhost:5000’. My Websocket server runs on ‘localhost:6000’.

I’ve had ChatGPT generate a simple Node-based websocket server (like mine) to see if the issue is with my server or if its something more general. Unfortunately, my browser clients weren’t able to connect to the ChatGPT generated server as well.

I’ve successfully managed to connect and interact with the Node Websocket servers using the Postman tool, so the issue seems to be browser-specific (I’ve tested various browsers, and they all yield the same results).

This is the code to the Node Websocket server generated by ChatGPT:

const WebSocket = require("ws");
const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("WebSocket server is running.");
});

const wss = new WebSocket.Server({ noServer: true });

wss.on("connection", (ws) => {
  console.log("Client connected");

  // Handle messages from clients
  ws.on("message", (message) => {
    console.log(`Received: ${message}`);

    // Echo the message back to the client
    ws.send(`Echo: ${message}`);
  });

  // Handle the closure of the WebSocket connection
  ws.on("close", () => {
    console.log("Client disconnected");
  });
});

server.on("upgrade", (request, socket, head) => {
  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit("connection", ws, request);
  });
});

const PORT = 6000;

server.listen(PORT, () => {
  console.log(`WebSocket server is listening on port ${PORT}`);
});

What could be the problem and how can I solve it?

Read more here: Source link