Skip to content

Instantly share code, notes, and snippets.

@gboddin

gboddin/udp2ws.js

Last active Aug 29, 2015
Embed
What would you like to do?
udp2ws.js
// 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);
<?
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);
}
}
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