簡體   English   中英

在 node.js 中使用 websockets 發送消息

[英]Send a message using websockets in node.js

地獄0那里!

今天我嘗試發送一條 websocket 消息。 我究竟做錯了什么? 我評論了下面的代碼,希望你們能理解我的目標......

// Import websocket
const websocket = require('ws');

// Create server
var socket = new websocket.Server({ port: 8080 })

// When client connects to websock server, reply with a hello world message
socket.on('connection', ws => {
    ws.send('{"message":"Hello world."}'); //This works.
});

function send_message(msg){
    ws.send(msg);
}

/* Calculate something, await for user interaction, etc... */

// When im done with all that, just send a message.
send_message('{"message":"please work"}'); // This does not work

我究竟做錯了什么?

您需要跟蹤連接。 你如何做到這一點取決於你

const websocket = require('ws');

const socket = new websocket.Server({ port: 8080 })

const connections = [];
socket.on('connection', ws => {
    connections.push(ws);
});

// send a new message to every connection once per second
setInterval(() => {
  const date = new Date();
  for (const ws of connections) {
    ws.send(`hello again: ${date}`);
  }
}, 1000);

當然,一個真正的應用程序可能會通過比一系列連接更復雜的東西來跟蹤連接。 當它們斷開連接等時,它還需要停止跟蹤這些連接......

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

我像這樣使用 WebSocket 來發送消息。

我希望這將幫助您解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM