Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

283
Vistas
Integrating websocket at React client

I am trying to connect a backend layer running on localhost, below is the source code:

const { createServer } = require("http");

const cors = require("cors");

const photos = require("./photos");

const app = require("express")();
const WebSocket = require("ws");

app.use(cors());

app.get("/", (req, res) => {
  res.status(200).json({});
});

app.get("/photos", (req, res) => {
  res.status(200).json({ photos });
});

const clients = new Set();

app.post("/photos/:id", (req, res) => {
  const photo = photos.find((p) => {
    return p.id === req.params.id;
  });

  photo.status= "PENDING";
  // Send back an approval
  const timeout = (3 + Math.floor(Math.random() * 4)) * 1000;
  setTimeout(() => {
    photo.status = "APPROVED";
    clients.forEach((ws) => {
      ws.send(JSON.stringify({ event: "APPROVED", photo }));
    });
  }, timeout);
  res.status(200).json({ photo });
});

const port = process.env.PORT || 3001;
const server = createServer(app);
server.listen(port, () => {
  console.log(`Starting server on port ${port}`);
});

const wss = new WebSocket.Server({ path: "/ws", server });
wss.on("connection", (ws) => {
  clients.add(ws);
  console.log("WebSocket connection established");

  ws.on("close", () => {
    clients.delete(ws);
    console.log("WebSocket connection closed");
  });
});

As on react client we can't use "ws" so I tried using both "websocket" package but I am not able to connect to "http" as it is not supported. Below is the source code:

import React from "react";
 import { w3cwebsocket as W3CWebSocket } from "websocket";

 const client = new W3CWebSocket('http://localhost:3001/ws');
// const client = new W3CWebSocket('ws://localhost:3001');

function App() {

  React.useEffect(
    () => {
      client.onopen = () => {
        console.log('WebSocket Client Connected');
      };
      client.onmessage = (message) => {
        console.log(message);
      };
    }, []
  )
     return null
}

Need help at client level to connect to 'http://localhost:3001/ws' to establish and listen connection.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are connecting to the wrong url. In following line on the server, you specify a path as /ws .

const wss = new WebSocket.Server({ path: "/ws", server });

So you need to connect to the specified path.

const client = new W3CWebSocket('ws://localhost:3001/ws');

If you remove the path: "/ws" from your createServer, the url ws://localhost:3001 (notice, no /ws path.. )should also work as expected.

Here's an example which worked on my machine ( without react, it's for showing socket connection.)

Client

var W3CWebSocket = require('websocket').w3cwebsocket;

const client = new W3CWebSocket('ws://localhost:3001/ws');

client.onopen = () => {
    console.log('WebSocket Client Connected');
};

client.onmessage = (message) => {
    console.log(message);
};
client.onerror = function() {
    console.log('Connection Error');
};

Server

const { createServer } = require("http");

const cors = require("cors");

const app = require("express")();
const WebSocket = require("ws");

app.use(cors());

const port = process.env.PORT || 3001;
const server = createServer(app);

server.listen(port, () => {
  console.log(`Starting server on port ${port}`);
});
const wss = new WebSocket.Server({ path: "/ws", server });
wss.on("connection", (ws) => {
  console.log("WebSocket connection established");

  ws.on("close", () => {
    console.log("WebSocket connection closed");
  });
});

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda