简体   繁体   中英

How to make a Server for Websocket secure with node.js

My websocket server, based on node.js, works for ws:// but not for wss://

The server runs on my Raspberry Pi B 3+. Now that I have changed ws:// to wss:// in my JavaScript file, it does not work anymore.

The node.js server:

const WebSocket = require('ws');
var wss = new WebSoket.Server({ port: 4445 });

wss.on('connection', function connection(ws) {
    console.log("New client connected.");

    ws.on('message', function incoming(data) {
        console.log(data);
        ws.close();
    });

    ws.on('close', function close() {
        console.log("Client disconnected.");
    });

});

The JavaScript client:

var connection = new Websocket('wss://myDomain:4445');

connection.onopen = function () {
    connection.send("Hello");
    connection.close();
}

connection.onerror = function (error) {
    console.log(error);
    connection.lose();
}

'myDomain' is a subdomain that refers to the IP of the Raspberry Pi via dns. I get the following error:

WebSocket connection to 'wss://myDomain:4445/' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

Maybe it will help you

Example:

Node server.js

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4445;
const index = require("./routes/index");
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server); 

let interval;
io.on("connection", socket => {
  console.log("New client connected");
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => getApiAndEmit(socket), 10000);
  socket.on("disconnect", () => {
    console.log("Client disconnected");
  });
});

const getApiAndEmit = async socket => {
    try {
      const res = await axios.get(
        "https://b.application.com/api/v1/scores?expand=createdBy"
      );
      socket.emit("FromAPI", res.data); // Emitting a new message. It will be consumed by the client
    } catch (error) {
      console.error(`Error: ${error.code}`);
    }
  };

server.listen(port, () => console.log(`Listening on port ${port}`));

Client in React

import socketIOClient from "socket.io-client";

class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      scores: []
      endpoint: "http://127.0.0.1:4445" 
    }
  }

componentDidMount() {
  const { endpoint } = this.state;

  const socket = socketIOClient(endpoint);

  socket.on("FromAPI", data => this.setState({ scores: data }));
}


  render () {
      <div>
      </div>
    )
  }
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM