2014-01-22 31 views
1

我遇到了一些問題。我正在使用socket.io(工作)連接到另一臺服務器,我想通過WS發送到客戶端(處理)。主要的問題是它只發送一次,我想發送socket.io所有的輸入。WS websocket send()作爲函數

實際代碼:

var io = require("socket.io-client"); 
var socket = io.connect('http://socket.io.server:8000'); 
var WebSocketServer = require('ws').Server 
, wss = new WebSocketServer({port: 8080}); 

var temp = 0; 

socket.on('connect', function() { 
    console.log("socket connected") ; 
}); 

socket.on('udp message', function(msg) { 
    temp = msg/100; 
    console.log(temp) ; 
    wss.on('connection', function(ws) { 
      ws.send(temp.toString()); 
    }); 
}); 

我想要的東西:

socket.on('udp message', function(msg) { 
    temp = msg/100; 
    console.log(temp) ; 
    ws.send(temp.toString()); 

}); 


wss.on('connection', function(ws) { 
    console.log("Connected to client") 
}); 

這樣我可以在我的WS客戶端有一個實時數據。

回答

1

如果只處理一個WebSocket的客戶端,你可以這樣做:如果你有多個WebSocket的客戶

var ws = null; 
socket.on('udp message', function(msg) { 
    var temp = msg/100; 
    console.log(temp); 
    // make sure we have a connection 
    if (ws !== null) { 
    ws.send(temp.toString()); 
    } 
}); 

wss.on('connection', function(_ws) { 
    console.log("Connected to client"); 
    ws = _ws; 
}); 

,你需要他們的_ws存儲在數組中,並與每個進入udp message事件,將其發送給存儲在該陣列中的每個WebSocket客戶端。

+0

它正常工作正常。謝謝!!! – user1343998

相關問題