Skip to content

Instantly share code, notes, and snippets.

@ZZR-china
Last active December 1, 2016 05:26
Show Gist options
  • Save ZZR-china/0b338e0ad6da7d9e819083443c1640a4 to your computer and use it in GitHub Desktop.
Save ZZR-china/0b338e0ad6da7d9e819083443c1640a4 to your computer and use it in GitHub Desktop.
websocket broadcast func , npm package use websocket (author theturtle32) and use timestamp as client uid
const PORT = parseInt(process.env.LEANCLOUD_APP_PORT || 3000);
app = express();
const server = require('http').createServer(app);
//WebSocket;
let clients = []; // list of currently connected clients (users)
const WebSocketServer = require('websocket').server;
const wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false,
maxReceivedFrameSize: 64 * 1024 * 1024, // 64MiB
maxReceivedMessageSize: 64 * 1024 * 1024, // 64MiB
});
let connection;
global.ws_client = clients;
clients.broadcast = function(message){
message = JSON.parse(message)
for (let i = 0, len = clients.length; i < len; i++) {
message.client_uid = clients[i].client_uid;
clients[i].send(JSON.stringify(message));
}
}
wsServer.on('request', function(request) {
let connection = request.accept('echo-protocol', request.origin);
// accept connection - you should check 'request.origin'
console.log((new Date()) + ' Connection from origin: ' + request.origin + '.');
const ws_time = (new Date()).getTime();
//ws time set be each client uid
connection.client_uid = ws_time;
const index = clients.push(connection) - 1;
const userName = "foowalaclient" + ws_time;
// user sent some message
connection.send(JSON.stringify({"client_uid" : ws_time}))
connection.on('message', function(message) {
if (message.type === 'utf8') {
clients.broadcast(JSON.stringify({"data" : ws_time}))
console.log((new Date()) + ' Received Message from ' + userName + ': ' + message.utf8Data);
}
});
// user disconnected
connection.on('close', function(connection) {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
// remove user from the list of connected clients
clients.splice(index, 1);
});
});
server.listen(PORT, function() {
console.log('Node app is running, port:', PORT);
// 注册全局未捕获异常处理器
process.on('uncaughtException', function(err) {
console.error("Caught exception:", err.stack);
});
process.on('unhandledRejection', function(reason, p) {
console.error("Unhandled Rejection at: Promise ", p, " reason: ", reason.stack);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment