server.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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', {
  28. root: path.resolve(__dirname + '/..')
  29. });
  30. });
  31. app.get('/json', function (req, res) {
  32. res.status(200).send();
  33. });
  34. io.sockets.on('connection', (socket) =>{
  35. console.log(`Connecté au client ${socket.id}`);
  36. const dgramCallback = function (buf) {
  37. // console.log(oscParser.decode(buf));
  38. socket.emit('osc', oscParser.decode(buf));
  39. };
  40. // forward UDP packets via socket.io
  41. udpSocket.on('message', dgramCallback);
  42. // prevent memory leak on disconnect
  43. socket.on('disconnect', function (socket) {
  44. udpSocket.removeListener('message', dgramCallback);
  45. });
  46. });
  47. // on change app par server
  48. server.listen(5000, function () {
  49. console.log('App frontend disponible sur localhost:5000 !')
  50. });