如何使用node.js使Websocket服务器安全

时间:2019-07-07 14:34:20

标签: javascript node.js websocket

我的websocket服务器基于node.js,可用于ws://,但不适用于wss://

服务器在我的Raspberry Pi B 3+上运行。现在,我已经在JavaScript文件中将ws://更改为wss://,它不再起作用。

node.js服务器:

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

});

JavaScript客户端:

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'是一个子域,它通过dns引用Raspberry Pi的IP。 我收到以下错误:

  

WebSocket连接到'wss:// myDomain:4445 /'失败:错误   建立连接:net :: ERR_CONNECTION_CLOSED

1 个答案:

答案 0 :(得分:0)

也许会对您有帮助

示例:

节点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}`));

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;