Skip to content

Instantly share code, notes, and snippets.

@ysugimoto
Created December 17, 2012 11:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ysugimoto/4317759 to your computer and use it in GitHub Desktop.
Save ysugimoto/4317759 to your computer and use it in GitHub Desktop.
WebSocket broadcast messaging from external protocol <Depends node-websocket-server>
var WebSocket = require('websocket').server,
Net = require('net'),
http = require('http'),
Dgram = require('dgram'),
unixPath = '/tmp/wsbroadcaster.sock',
unixSocket,
udpSocket,
wsServer,
httpServer;
// Create HTTP Server
httpServer = http.createServer(function(request, response) {
response.writeHead(404, {"Content-Type": 'text/plain'});
response.write('Page Not Found.');
response.end();
});
httpServer.listen(8124);
// Create WebSocket Server
wsServer = new WebSocket({
httpServer: httpServer,
autoAcceptConnections: true
});
// WebSocket events
wsServer.on('connect', function(connection) {
console.log('WebSocket connected.');
connection.on('message', function(msg) {
wsServer.broadcast(msg);
})
});
// Create udp Socket
udpSocket = Dgram.createSocket('udp4');
udpSocket.on('message', function(message, info) {
console.log('UDP request handled.');
wsServer.broadcast(message.toString('utf8', 0, info.size));
});
udpSocket.on('listening', function() {
console.log('UDP Server bound at ' + udpSocket.address().address + ':' + udpSocket.address().port);
});
udpSocket.bind(8125); // listening 0.0.0.0:8125
// Create Unix Socket
unixSocket = Net.createServer(function(connection) {
console.log('UNIX Socket handled.');
connection.setEncoding('utf8');
connection.on('data', function(chunk) {
wsServer.broadcast(chunk);
});
})
unixSocket.listen(unixPath, function() {
console.log('UNIX Socket bound.');
// do something for listen started.
});
// SIGINT Event bind
process.on('SIGINT', function() {
udpSocket.close();
unixSocket.close();
process.exit();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment