admin管理员组

文章数量:1357615

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.

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.

Share Improve this question asked Oct 29, 2021 at 13:55 CoderInUiCoderInUi 1362 gold badges4 silver badges12 bronze badges 3
  • If you have no a lot understanding of sockets (like me), I suggest to use socket.io package => npmjs./package/socket.io It's a wrapper for websockets. – Silvan Bregy Commented Oct 29, 2021 at 14:24
  • Yes but it is a two way thing but I don't want to change the server code, just need to add the code on client side. – CoderInUi Commented Oct 29, 2021 at 14:42
  • stackoverflow./questions/76810467/… Is there some obvious issue here – Basu Commented Aug 1, 2023 at 10:10
Add a ment  | 

1 Answer 1

Reset to default 5

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

本文标签: javascriptIntegrating websocket at React clientStack Overflow