【问题标题】:How to make a Server for Websocket secure with node.js如何使用 node.js 使 Websocket 服务器安全
【发布时间】:2019-07-07 14:34:20
【问题描述】:

我的基于 node.js 的 websocket 服务器适用于 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 引用树莓派的 IP。 我收到以下错误:

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

【问题讨论】:

    标签: javascript node.js websocket


    【解决方案1】:

    也许对你有帮助

    例子:

    节点 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;
    

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 2015-09-29
      • 2021-09-14
      • 2014-02-13
      相关资源
      最近更新 更多