Skip to content

Instantly share code, notes, and snippets.

@ChuckJHardy
Last active October 22, 2021 23:03
Show Gist options
  • Save ChuckJHardy/6706045 to your computer and use it in GitHub Desktop.
Save ChuckJHardy/6706045 to your computer and use it in GitHub Desktop.
ZeroMQ + Node.js + Socket.io + UI for sending message from Ruby to a Javascript UI running on Node.js

Install the following requirements:

brew info zeromq
npm install zmq
npm install socket.io
gem install ffi-rzmq

Within the app directory run the following commands in different panes.

ruby worker.rb
node app.js
ruby ventilator.rb
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
zmq = require('zmq'),
receiver = zmq.socket('pull');
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.configure( function(){
io.set('log level', 3);
io.set('transports', [ 'websocket', ]);
});
io.sockets.on('connection', function (socket) {
receiver.on('message', function(message) {
socket.emit('marker', { 'message': escape(message) });
});
});
receiver.bindSync("tcp://*:5558");
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('marker', function (data) {
console.log(data.message);
});
</script>
require 'rubygems'
require 'ffi-rzmq'
context = ZMQ::Context.new(1)
# Socket to send messages on
sender = context.socket(ZMQ::PUSH)
sender.bind("tcp://*:5557")
# The first message is "0" and signals start of batch
sender.send_string('0')
# Send 50 tasks
50.times do |workload|
$stdout << "#{workload}."
sender.send_string(workload.to_s)
sleep(0.2)
end
Kernel.sleep(1) # Give 0MQ time to deliver
require 'rubygems'
require 'ffi-rzmq'
context = ZMQ::Context.new(1)
# Socket to receive messages on
receiver = context.socket(ZMQ::PULL)
receiver.connect("tcp://localhost:5557")
# Socket to send messages to
sender = context.socket(ZMQ::PUSH)
sender.connect("tcp://localhost:5558")
# Process tasks forever
while true
receiver.recv_string(msec = '')
$stdout << "#{msec}."
sender.send_string(msec)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment