Skip to content

Instantly share code, notes, and snippets.

@lkishfy
Created August 27, 2018 00:11
Show Gist options
  • Select an option

  • Save lkishfy/fc9a57678797a35984c58c8b000c81f2 to your computer and use it in GitHub Desktop.

Select an option

Save lkishfy/fc9a57678797a35984c58c8b000c81f2 to your computer and use it in GitHub Desktop.
Node Server for reading and emitting UDP Datagrams from server to client with Socket.IO
///////////////////////////////////////////////////INITIALIZE VARIABLES
var express = require('express')
const url = require('url');
var app = express()
var $ = require('jquery');
var dgram = require('dgram');
var udpServer = dgram.createSocket('udp4');
var PORT = 41234;
var HOST = '127.0.0.1';
var SerialPort = require("serialport");
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server, { wsEngine: 'ws' });
var port = process.env.PORT || 3000;
var lastPosition;
var lastDirection;
///////////////////////////////////////////////////INITIALIZE VARIABLES
///////////////////////////////////////////////////SEND DATA TO CLIENT SIDE
udpServer.on('error', (err) => {
console.log('server error');
});
udpServer.on('message', (msg, rinfo) => {
//This example is for an RLS rotary encoder
var encoderData = msg.toString();
var splitEncoderData = encoderData.split(':',3);
var position = splitEncoderData[0];
var direction = position - lastPosition;
var speed = Math.abs((direction > 20) ? 20 : direction);
lastPosition = position; // update last position (after using current position)
lastDirection = directionq; // update last direction
io.sockets.emit('position', position, speed, direction);
});
udpServer.bind(PORT, HOST);
///////////////////////////////////////////////////SEND DATA TO CLIENT SIDE
///////////////////////////////////////////////////PAGE RENDERING
app.use(express.static(__dirname + '/Views'));
server.listen(3000, function listening() {
console.log('Listening on %d', server.address().port);
});
app.get('/', function (req, res) {
res.sendFile('index.html');
})
//////////////////////////////////////////////////PAGE RENDERING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment