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);
作爲聲明,但它不起作用。
難道僅僅是在一個錯字問題,還是你我們e在connectedClients/connectedclients上使用不同大小寫的代碼? –
我使用相同的大寫字母(現在編輯)... – auino