server.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const express = require('express');
  2. const dgram = require('dgram');
  3. const oscParser = require('./osc-parser');
  4. const bodyParser = require('body-parser');
  5. const path = require('path');
  6. const app = express();
  7. const server = require('http').Server(app);
  8. const io = require('socket.io')(server, {
  9. transports: ['websocket']
  10. });
  11. const onSocketListening = function() {
  12. const address = udpSocket.address();
  13. console.log('Serveur TUIO en écoute sur : ' + address.address + ':' + address.port);
  14. };
  15. const onSocketConnection = function(socket) {
  16. udpSocket.on('message', function(msg) {
  17. socket.emit('osc', oscParser.decode(msg));
  18. });
  19. };
  20. const udpSocket = dgram.createSocket('udp4');
  21. udpSocket.on('listening', onSocketListening);
  22. udpSocket.bind(3333, '127.0.0.1');
  23. app.use(bodyParser.json());
  24. app.use(bodyParser.urlencoded({extended:true}));
  25. app.use(express.static('./frontend/assets'));
  26. app.get('/', function (req, res) {
  27. res.sendFile('./frontend/index.html', { root: path.resolve(__dirname + '/..') });
  28. });
  29. app.get('/json', function (req, res) {
  30. res.status(200).json({'message': 'ok'})
  31. });
  32. io.sockets.on('connection', (socket) =>{
  33. console.log(`Connecté au client ${socket.id}`);
  34. const dgramCallback = function (buf) {
  35. console.log(oscParser.decode(buf));
  36. socket.emit('osc', oscParser.decode(buf));
  37. };
  38. // forward UDP packets via socket.io
  39. udpSocket.on('message', dgramCallback);
  40. // prevent memory leak on disconnect
  41. socket.on('disconnect', function (socket) {
  42. udpSocket.removeListener('message', dgramCallback);
  43. });
  44. });
  45. // on change app par server
  46. server.listen(5000, function () {
  47. console.log('App frontend disponible sur localhost:5000 !')
  48. });