简体   繁体   English

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

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

I am trying to learn how websockets work. 我正在尝试学习websockets的工作方式。 I am able to get trading data from a websocket server and print it on the console. 我能够从websocket服务器获取交易数据并将其打印在控制台上。 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. 但是,我试图了解如何将该消息传递到我的websocket服务器,以便可以将其发送到我的websocket客户端。 Basically, I want to print each message on browser. 基本上,我想在浏览器上打印每条消息。

"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 binanceWS will print data when it recieves one. 现在,该binanceWS将在binanceWS数据时打印数据。 The thing I am trying to do is how I can pass to the send eventlistener of my WebSocket.Server object. 我正在尝试做的事情是如何传递给WebSocket.Server对象的send eventlistener。 As you can see an example from https://github.com/websockets/ws wss itself takes a websocket object when there is a connection. 您可以从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. 基本上,我将让websocket消费者获取交易数据。 And within same host (localhost for now) there will be a websocket server. 在同一主机(目前为localhost)中,将有一个websocket服务器。 This websocket server will send data to each client websockets. 该websocket服务器将向每个客户端websocket发送数据。

在此处输入图片说明

SUCCESS : Ok I made it by defining consumer websocket ( binanceWS ) message listener in websocket server connection. 成功 :好的,我是通过在websocket服务器连接中定义使用者websocket( binanceWSmessage侦听器来实现的。 I am not sure if this is a good way though 我不确定这是否是一个好方法

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

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 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

I achieved this my keeping a global list for websocket clients. 我做到了这一点,为Websocket客户保留了一份全球清单。 And when consumer websocket message event is triggered, it sends every client by traversing list. 当消费者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");
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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