javascript websockets - 从 websocket 服务器获取消息并将其发送到客户端

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50618425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:12:29  来源:igfitidea点击:

websockets - get message from a websocket server and send it to client

javascriptnode.jswebsocket

提问by quartaela

I am trying to learn how websockets work. I am able to get trading data from a websocket server and print it on the console. However, I am trying to understand how I can pass that message into my websocket server so that I can send it to my websocket clients. Basically, I want to print each message on browser.

我正在尝试学习 websockets 是如何工作的。我能够从 websocket 服务器获取交易数据并将其打印在控制台上。但是,我试图了解如何将该消息传递到我的 websocket 服务器,以便我可以将其发送到我的 websocket 客户端。基本上,我想在浏览器上打印每条消息。

"use strict";

const WebSocket = require("ws");

const binanceWS = new WebSocket("wss://stream.binance.com:9443/ws/stratbtc@trade");

binanceWS.on("open", function open() {
    console.log("open action");
});

binanceWS.on("message", function incoming(data) {
    console.log(data);
});

Now this binanceWSwill print data when it recieves one. The thing I am trying to do is how I can pass to the sendeventlistener of my WebSocket.Server object. As you can see an example from https://github.com/websockets/wswss itself takes a websocket object when there is a connection.

现在这binanceWS将在收到数据时打印数据。我想做的是如何传递给send我的 WebSocket.Server 对象的事件侦听器。正如您从https://github.com/websockets/ws看到的一个示例,当有连接时,wss 本身采用 websocket 对象。

const wss = new WebSocket.Server({ port: 8080 });

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

  ws.send('something');
});

Thanks!

谢谢!

NOTE: The structure I am talking about is like this. Basically, I will have websocket consumers to get trade data. And within same host (localhost for now) there will be a websocket server. This websocket server will send data to each client websockets.

注意:我所说的结构是这样的。基本上,我将让 websocket 消费者获取交易数据。并且在同一主机(现在是 localhost)中会有一个 websocket 服务器。该 websocket 服务器将向每个客户端 websocket 发送数据。

enter image description here

在此处输入图片说明

SUCCESS: Ok I made it by defining consumer websocket (binanceWS) messagelistener in websocket server connection. I am not sure if this is a good way though

成功:好的,我通过在 websocket 服务器连接中定义消费者 websocket ( binanceWS)message侦听器来实现的。我不确定这是否是一个好方法

"use strict";

const WebSocket = require("ws");

const binanceWS = new WebSocket("wss://stream.binance.com:9443/ws/stratbtc@trade");

binanceWS.on("open", function open() {
    console.log("open action");
});

const wss = new WebSocket.Server({ port: 8080 });

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

  binanceWS.on("message", function incoming(data) {
      ws.send(data);
  });
});

采纳答案by quartaela

I achieved this my keeping a global list for websocket clients. And when consumer websocket message event is triggered, it sends every client by traversing list.

我实现了这一点,我为 websocket 客户端保留了一个全局列表。并且当消费者 websocket 消息事件被触发时,它通过遍历列表发送每个客户端。

"use strict";

const WebSocket = require("ws");

const binanceWS = new WebSocket("wss://stream.binance.com:9443/ws/eosbtc@trade");

var websocketList = [];

binanceWS.on("open", function open() {
    console.log("open action");
});

binanceWS.on("message", function incoming(data) {
    console.log(data);

    // send data to every websocket client
    websocketList.forEach(ws => {
        ws.send(data);
    });
});

const wss = new WebSocket.Server({ port: 8080 });

wss.on("connection", function connection(ws) {

    // add ws handle to websocket list.
    websocketList.push(ws);

    ws.on("close", function close() {
        console.log("Disconnected");
    });
});

回答by edkeveked

single websocket

单个网络套接字

//websocket connection event will return a socket you can later use
binanceWS.on("connection", function(socket) {
    socket.on("message", function incoming(data) {
    console.log(data);
    // if you want to send that message back to the client who sent it, 
    // you can use send method on the socket
     socket.send(data)
    });
});

Nesting websocket

嵌套 websocket

//websocket connection event will return a socket you can later use
binanceWS.on("connection", function(socket) {
    // create another websocket here
    const wss = new WebSocket.Server({ port: 8080 });

    // connect the second websocket
     wss.on("connection", function(ws) {
      // start listening to first websocket incoming messages 
      // if second communication has successully been instantiated 
      socket.on("message", function incoming(data) {
      // send the data using the second websocket
      ws.send(data)
      })
    });
});

Then you need to have this minimum code in your client and you will see the interaction between the server and your client

然后你需要在你的客户端中有这个最少的代码,你会看到服务器和你的客户端之间的交互

client

客户

const socket = new WebSocket('server_url'); // Connection opened 
socket.addEventListener('message', function (event) { socket.send('send message'); });

Note: Since you will use the incoming data of a websocket into another, it is best to open the second websocket only if the first one has successfully been opened

注意:由于你会将一个websocket的传入数据用到另一个websocket中,所以最好只有在第一个websocket成功打开后才打开第二个websocket