UNPKG

node-insim

Version:

An InSim library for NodeJS with TypeScript support

83 lines (82 loc) 2.99 kB
import * as dgram from 'dgram'; import { log as baseLog } from '../log'; import { Protocol } from './Protocol'; const log = baseLog.extend('udp'); /** @internal */ export class UDP extends Protocol { constructor({ host, port, socketInitialisationMode, packetSizeMultiplier = 1, timeout = 0, }) { super({ host, port, packetSizeMultiplier }); this.socket = null; this.timeout = 0; this.timeoutTimer = null; this.connect = () => { this.socket = dgram.createSocket('udp4'); log(`Connecting to ${this.host}:${this.port}...`); if (this.socketInitialisationMode === 'bind') { this.socket.bind({ address: this.host, port: this.port, }); this.socket.on('listening', () => { log('Listening'); this.emit('connect'); }); } else if (this.socketInitialisationMode === 'connect') { this.socket.connect(this.port, this.host); this.socket.on('connect', () => { log('Connected'); this.emit('connect'); }); } if (this.timeout > 0) { this.timeoutTimer = setTimeout(this.handleTimeout, this.timeout); } this.socket.on('close', () => { log('Connection closed'); this.emit('disconnect'); }); this.socket.on('error', (error) => { log('Error', error); this.emit('error', error); }); this.socket.on('message', (data) => { log('Data received:', data.join()); this.emit('data', data); if (this.timeoutTimer) { clearTimeout(this.timeoutTimer); } if (this.timeout) { this.timeoutTimer = setTimeout(this.handleTimeout, this.timeout); } }); }; this.disconnect = () => { if (this.socket === null) { log('Cannot disconnect - not connected'); return; } this.socket.close(); if (this.timeoutTimer) { clearTimeout(this.timeoutTimer); this.timeoutTimer = null; } }; this.send = (data) => { if (this.socket === null) { log('Cannot send - not connected'); return; } log('Send data:', data.join()); this.socket.send(data); }; this.handleTimeout = () => { log('Connection timed out'); this.emit('timeout'); this.timeoutTimer = null; this.disconnect(); }; this.timeout = timeout; this.socketInitialisationMode = socketInitialisationMode; } }