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