2012-09-11 83 views
2

我有一個Node.js的服務器websocket模塊,可以通過以下命令安裝之間共享信息:的WebSocket上的Node.js和所有連接的客戶端

npm install websocket 

this guide開始,我決定擴展它共享所有客戶端之間發送的消息。

這是我(簡化)服務器代碼:

#!/usr/bin/env node 
var WebSocketServer = require('websocket').server; 
var http = require('http'); 

var server = http.createServer(function(request, response) { 
    console.log((new Date()) + ' Received request for ' + request.url); 
    response.writeHead(404); 
    response.end(); 
}); 
server.listen(8080, function() { 
    console.log((new Date()) + ' Server is listening on port 8080'); 
}); 

wsServer = new WebSocketServer({ 
    httpServer: server, 
    autoAcceptConnections: false 
}); 

var connectedClientsCount = 0; // ADDED 
var connectedClients = []; // ADDED 

wsServer.on('request', function(request) { 
    var connection = request.accept('echo-protocol', request.origin); 
    connectedClientsCount++; 
    connectedClients.push(connection); 
    console.log((new Date()) + ' Connection accepted.'); 
    connection.on('message', function(message) { 
     if (message.type === 'utf8') { 
      console.log('Received Message: ' + message.utf8Data); 
      for(c in connectedClients) // ADDED 
       c.sendUTF(message.utf8Data); // ADDED 
     } 
     else if (message.type === 'binary') { 
      console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); 
      connection.sendBytes(message.binaryData); 
     } 
    }); 
    connection.on('close', function(reasonCode, description) { 
     // here I should delete the client... 
     console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); 
    }); 
}); 

在這種情況下,我可以得到connectedClientsCount價值,但我不能管理connectedClients列表。

我也試着用((eval)c).sendUTF(message.utf8Data);作爲聲明,但它不起作用。

+0

難道僅僅是在一個錯字問題,還是你我們e在connectedClients/connectedclients上使用不同大小寫的代碼? –

+0

我使用相同的大寫字母(現在編輯)... – auino

回答

5

我建議你使用Socket.IO:實時應用程序的跨瀏覽器WebSocket。該模塊是install and configure

例如很簡單: 服務器

... 
io.sockets.on('connection', function (socket) { 
    //Sends the message or event to every connected user in the current namespace, except to your self. 
    socket.broadcast.emit('Hi, a new user connected'); 

    //Sends the message or event to every connected user in the current namespace 
    io.sockets.emit('Hi all'); 

    //Sends the message to one user 
    socket.emit('news', {data:'data'}); 
    }); 
}); 
... 

more

客戶:

<script src="/socket.io/socket.io.js"></script> 
<script> 
    var socket = io.connect('http://localhost'); 
    //receive message 
    socket.on('news', function (data) { 
    console.log(data); 
    //send message 
    socket.emit('my other event', { my: 'data' }); 
    }); 
</script> 

更多exposed events

相關問題