在微服务应用程序中实现 websockets

Hei*_*rme 6 websocket node.js spring-boot angular

我有一个非常复杂的练习,但到目前为止我做得很好。我唯一要做的就是将 WebSockets 添加到组合中。

这是一个关于两个主题的简单投票应用程序,但我必须使用特定技术才能在特定部分使用。此外,一切都在 Docker 中运行。

这是我的应用程序的架构:

建筑学

目前该应用程序适用于 HTTP 请求,但我必须以某种方式实现 WebSockets。我知道我必须链接 Angular,但另一个是什么?

在这种情况下,我将如何实现 WebSockets?

O. *_*nes 2

Websocket 与 https 有很多共同点。事实上,它们以 https 连接开始,然后升级持久的 websocket 连接。

因此,您的客户端(浏览器中的 JavaScript)使用WebSocket 对象的实例发起连接。然后它可以向服务器发送消息并从服务器接收消息。您的浏览器代码可能如下所示。它启动一个连接。当连接打开时,它会发送一条消息。

const ws = new WebSocket("ws://www.example.com:8090/socketserver");

ws.onmessage = function (event) {
    console.log ('incoming', event.data);
}

ws.onopen = function (event) {
    ws.send ("Hey there server!");
}
Run Code Online (Sandbox Code Playgroud)

在服务器(nodejs)端,您需要安装一个 websocket 服务器来接受客户端连接。您可以使用npm 的 ws package来完成此操作。(还有其他软件包,但我知道这个有效。)

您的最小可行 ws 服务器代码也非常简单。

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

wss.on('connection', function connection(ws) {
  /* Here an incoming websocket connection is accepted 
   * You must keep the ws object in scope for the lifetime
   * of the connection */

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  /* respond to ping keepalives from client */
  ws.on('ping', function ping() {
      ws.pong();
  }

  /* send messages as needed */
  ws.send('hey there client!');
});
Run Code Online (Sandbox Code Playgroud)

请注意:浏览器安全性不允许您混合从浏览器到服务器的连接模式(https / http)。因此,如果前端的其余部分通过 https: 提供服务,则需要使用 wss: 而不是 ws:。在服务器端安装有点困难,但仍然以相同的方式工作。

另请注意,我没有给出任何错误或超时处理。生产代码需要这些东西。