Home > Software engineering >  Integrating websocket at React client
Integrating websocket at React client

Time:10-30

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.

CodePudding user response:

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");
  });
});

  • Related