NodeJS Websocket(ws)如何在不同客户端之间进行通信?

时间:2017-08-21 15:33:13

标签: javascript json node.js ajax websocket

我有2个客户端,我需要client1向client2提供信息并收到它的警告,我正在用NodeJS实现Websocket“ws”。

Client1网页通过AJAX接收答案,并以JSON格式向server.js发送信息,如下例所示: 的 /mysite_folder/client1/client1.php

<script>
var userorder = $("#user").val(); //client2 username who will receive information

$.post("myscript.php",{
  my: variables
}).done(function(response){
var wsUri = "wss://www.mysite.com:3000/sockets/";
var output;

websocket = new WebSocket(wsUri);
websocket.onopen = onOpen; 
websocket.onclose = onClose; 
websocket.onmessage = onMessage;
websocket.onerror = onError;

function onOpen(evt){

output = {
 "status": "ASSIGNED",
 "user":  userorder
 };
 doSend(JSON.stringify(output));
}

function doSend(message){ 
 websocket.send(message);
 websocket.close();
}

function onMessage(evt){    
}

function onClose(evt){ 
 location.reload();
}

function onError(evt){
}
});

</script>

在client1发送信息后,连接关闭并刷新client1页面。我的服务器收到这样的JSON信息: /mysite_folder/sockets/server.js

var WebSocketServer = require('ws').Server,
fs = require('fs');

var cfg = {
    ssl: true,
    port: 3000,
    ssl_key: '/path/of/sslkey',
    ssl_cert: '/path/of/sslcert'
};

var httpServ = ( cfg.ssl ) ? require('https') : require('http');

var app      = null;

var processRequest = function( req, res ) {
res.writeHead(200);
res.end("All glory to WebSockets!\n");
};

if ( cfg.ssl ) {

app = httpServ.createServer({

   // providing server with  SSL key/cert
   key: fs.readFileSync( cfg.ssl_key ),
   cert: fs.readFileSync( cfg.ssl_cert )

}, processRequest ).listen( cfg.port );

} else {
 app = httpServ.createServer( processRequest ).listen( cfg.port );
}

var wss = new WebSocketServer( { server: app } );
wss.on('connection', function connection(ws){
console.log("User connected");

 ws.on('message', function incoming(message){      
   var info = JSON.parse(message); //receive client1 info
   if(info.status=="ASSIGNED"){
     ws.send(info.user); //send client2 username
   }       
 });
});

解析JSON并比较该信息状态为“ASSIGNED”我需要将“info.user”发送到显示警告消息的client2页面,因此在client2中我写了这样的例子: /mysite_folder/client2/client2.php

$(document).ready(function(){
 var user = $("#user").val(); //client2 username

 var wsUri = "wss://www.mysite.com:3000/sockets/";
 var output;

 websocket = new WebSocket(wsUri);
 websocket.onopen = onOpen;
 websocket.onclose = onClose;
 websocket.onmessage = onMessage;
 websocket.onerror = onError;

 function onOpen(evt){
 }

 function doSend(message){
 }

 function onMessage(evt){ 
  if(user==evt){ //if client2 username sent by server is the same with client2 username logged in the page, make an alert
    alert("Your order was ASSIGNED");
  }
  websocket.close();
 }

 function onClose(evt){
 }

 function onError(evt){
 }
});

Connections工作正常,client1运行良好,但在client2中没有发生任何事情,我如何让client2获得此警报?

更新

server.js 上,我添加了这样的广播方法:

var wss = new WebSocketServer( { server: app } );

// Broadcast to all.
wss.broadcast = function broadcast(data) {
  wss.clients.forEach(function each(client) {
  if ( client.readyState == WebSocketServer.OPEN) {
    client.send(data);
  }      
  });
};

wss.on('connection', function connection(ws){
console.log("User connected");

ws.on('message', function incoming(message){

    //Broadcast to everyone else
    var info = JSON.parse(message);
    console.log(info.user); //shows username in console

    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocketServer.OPEN) {
        if(info.status=="ASSIGNED"){
            client.send(info.user);
        }
      }
    });     
});
});

但是client2仍然没有从服务器接收消息而没有显示警报。

我想要一些帮助。

1 个答案:

答案 0 :(得分:0)

问题是您在收到消息的同一套接字连接中发回数据,即ws.send(info.user)ws仅指该客户端连接。

服务器有一个broadcast方法,可以将消息发送到所有活动连接

wss.broadcast(info.user);