Last active
August 29, 2015 14:00
-
-
Save gboddin/11275594 to your computer and use it in GitHub Desktop.
udp2ws.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Bridging upd datagrams to websockets using a nodejs app | |
// Listening on udp://0.0.0.0:41234 | |
// Broadcasting on ws://0.0.0.0:8080 | |
// -> https://github.com/einaros/ws | |
var WebSocketServer = require('ws').Server; | |
var dgram = require("dgram"); | |
var ServerWS = new WebSocketServer({port: 8080}); | |
var ServerUDP = dgram.createSocket("udp4"); | |
ServerUDP.on("message", function (msg, rinfo) { | |
for(var i in ServerWS.clients) | |
ServerWS.clients[i].send(msg.toString('utf8')); | |
console.log('Received and forwarded' + msg.toString('utf8')); | |
}); | |
ServerUDP.bind(41234); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
class zBus { | |
static $instance = null; | |
static $socket = null; | |
static $ip = '127.0.0.1'; //replace by multicast IP if needed | |
static $port = '41234'; | |
static function getInstance() { | |
if(is_null(self::$instance)) { | |
self::$instance = new self(); | |
self::$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); | |
} | |
return self::$instance; | |
} | |
public function broadcast($data) { | |
return socket_sendto(self::$socket,json_encode($data),strlen(json_encode($data)),0,self::$ip,self::$port); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ws = new WebSocket('ws://127.0.0.1:8080'); | |
ws.onmessage = function(msg) { | |
window.console.log(msg); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment