1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | 'use strict';
|
22 |
|
23 | var dgram = require('dgram'),
|
24 | EventEmitter = require('events').EventEmitter,
|
25 | net = require('net'),
|
26 | util = require('util'),
|
27 | UDPSocket = require('./utils').UDPSocket,
|
28 | TCPSocket = require('./utils').TCPSocket,
|
29 | Packet = require('./packet');
|
30 |
|
31 | var Server = function(opts) {
|
32 | var self = this;
|
33 |
|
34 | this._socket.on('listening', function() {
|
35 | self.emit('listening');
|
36 | });
|
37 |
|
38 | this._socket.on('close', function() {
|
39 | self.emit('close');
|
40 | });
|
41 |
|
42 | this._socket.on('error', function(err) {
|
43 | self.emit('socketError', err, self._socket);
|
44 | });
|
45 | };
|
46 | util.inherits(Server, EventEmitter);
|
47 |
|
48 | Server.prototype.close = function() {
|
49 | this._socket.close();
|
50 | };
|
51 |
|
52 | Server.prototype.address = function() {
|
53 | return this._socket.address();
|
54 | };
|
55 |
|
56 | Server.prototype.handleMessage = function(msg, remote, address) {
|
57 | var request, response = new Packet(remote);
|
58 |
|
59 | try {
|
60 | request = Packet.parse(msg, remote);
|
61 |
|
62 | request.address = address;
|
63 |
|
64 | response.header.id = request.header.id;
|
65 | response.header.qr = 1;
|
66 | response.question = request.question;
|
67 |
|
68 | this.emit('request', request, response);
|
69 | } catch (e) {
|
70 | this.emit('error', e, msg, response);
|
71 | }
|
72 | };
|
73 |
|
74 | var UDPServer = function(opts) {
|
75 | var self = this;
|
76 |
|
77 | this._socket = dgram.createSocket(opts.dgram_type || 'udp4');
|
78 |
|
79 | this._socket.on('message', function(msg, remote) {
|
80 | self.handleMessage(msg, new UDPSocket(self._socket, remote), remote);
|
81 | });
|
82 |
|
83 | Server.call(this, opts);
|
84 | };
|
85 | util.inherits(UDPServer, Server);
|
86 |
|
87 | UDPServer.prototype.serve = function(port, address) {
|
88 | this._socket.bind(port, address);
|
89 | };
|
90 |
|
91 | var TCPServer = function(opts) {
|
92 | var self = this;
|
93 |
|
94 | this._socket = net.createServer(function(client) {
|
95 | var tcp = new TCPSocket(client);
|
96 | var address = client.address();
|
97 | tcp.on('message', function(msg, remote) {
|
98 | self.handleMessage(msg, tcp, address);
|
99 | });
|
100 | tcp.catchMessages();
|
101 | });
|
102 |
|
103 | Server.call(this, opts);
|
104 | };
|
105 | util.inherits(TCPServer, Server);
|
106 |
|
107 | TCPServer.prototype.serve = function(port, address) {
|
108 | this._socket.listen(port, address);
|
109 | };
|
110 |
|
111 | exports.createServer = function(opts) {
|
112 | return new UDPServer(opts || {});
|
113 | };
|
114 |
|
115 | exports.createUDPServer = function(opts) {
|
116 | return exports.createServer(opts);
|
117 | };
|
118 |
|
119 | exports.createTCPServer = function(opts) {
|
120 | return new TCPServer(opts || {});
|
121 | };
|