Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var dgram = require('dgram');
- var port = 3000;
- var defaultSize = 65;
- function Server()
- {
- var clients = [];
- var socket = dgram.createSocket('udp4');
- socket.on('message', function (msg, rinfo) {
- var clientId, message;
- message = msg.toString('ascii');
- console.log(message);
- clientId = rinfo.address + ':' + rinfo.port;
- if(message.match('<JOIN>')) {
- console.log('Client connected: ', clientId);
- if ( !clients[clientId] ) {
- clients[clientId] = rinfo;
- }
- return;
- }
- if ( message.match('<EXIT>') ) {
- console.log('Client disconnected: ', clientId);
- if ( clients[clientId] ) {
- delete clients[clientId];
- }
- return;
- }
- for ( var client in clients ) {
- if ( client !== clientId) {
- client = clients[client];
- socket.send(new Buffer(message, 'ascii'), 0, Buffer.byteLength(message, 'ascii'), client.port, client.address, function ( err, bytes ) {
- if ( err ) console.error(err);
- console.log('Client sent: ', bytes);
- });
- }
- }
- /* ТОВА ТРЯБВА ДА ГО ИМА ЗА ДА ОСЪЩЕСТВЯ ВРЪЗКА И ДА МОГА ДА ПОЛЗВАМ СОКЕТА */
- //socket.send(msg, 0, msg.length, rinfo.port, rinfo.address, function ( err, bytes ) {
- // if ( err ) throw err;
- //});
- });
- socket.on('listening', function () {
- console.log('Server ready: ', socket.address());
- });
- socket.on('close', function () {
- console.log('Socket closed');
- });
- socket.on('error', function ( err ) {
- console.error('Server ERROR: ', err);
- socket.close();
- });
- socket.bind(port, '127.0.0.1');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement