Advertisement
relax4o

udp_server

Dec 17th, 2015
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var dgram = require('dgram');
  2. var port = 3000;
  3. var defaultSize = 65;
  4.  
  5. function Server()
  6. {
  7.     var clients = [];
  8.     var socket = dgram.createSocket('udp4');
  9.  
  10.     socket.on('message', function (msg, rinfo) {
  11.         var clientId, message;
  12.  
  13.         message = msg.toString('ascii');
  14.         console.log(message);
  15.  
  16.         clientId = rinfo.address + ':' + rinfo.port;
  17.         if(message.match('<JOIN>')) {
  18.             console.log('Client connected: ', clientId);
  19.  
  20.             if ( !clients[clientId] ) {
  21.                 clients[clientId] = rinfo;
  22.             }
  23.             return;
  24.         }
  25.  
  26.         if ( message.match('<EXIT>') ) {
  27.             console.log('Client disconnected: ', clientId);
  28.             if ( clients[clientId] ) {
  29.                 delete clients[clientId];
  30.             }
  31.             return;
  32.         }
  33.  
  34.         for ( var client in clients ) {
  35.             if ( client !== clientId) {
  36.                 client = clients[client];
  37.  
  38.                 socket.send(new Buffer(message, 'ascii'), 0, Buffer.byteLength(message, 'ascii'), client.port, client.address, function ( err, bytes ) {
  39.                     if ( err ) console.error(err);
  40.                     console.log('Client sent: ', bytes);
  41.                 });
  42.             }
  43.         }
  44.        
  45.         /* ТОВА ТРЯБВА ДА ГО ИМА ЗА ДА ОСЪЩЕСТВЯ ВРЪЗКА И ДА МОГА ДА ПОЛЗВАМ СОКЕТА */
  46.         //socket.send(msg, 0, msg.length, rinfo.port, rinfo.address, function ( err, bytes ) {
  47.         //  if ( err ) throw err;
  48.         //});
  49.     });
  50.  
  51.     socket.on('listening', function () {
  52.         console.log('Server ready: ', socket.address());
  53.     });
  54.  
  55.     socket.on('close', function () {
  56.         console.log('Socket closed');
  57.     });
  58.  
  59.     socket.on('error', function ( err ) {
  60.         console.error('Server ERROR: ', err);
  61.         socket.close();
  62.     });
  63.  
  64.     socket.bind(port, '127.0.0.1');
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement