forked from lkiesow/nodejs-irc-webclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
irc_gateway.js
92 lines (80 loc) · 2.17 KB
/
irc_gateway.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var net = require("net");
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
var port = process.argv.length == 3 ? Number( process.argv[2] ) : 8080;
/**
* \brief Webserver to deliver client files.
* @param req the request
* @param res the response
*/
app.listen( port );
function handler (req, res) {
fs.readFile(__dirname + '/irc_client.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.setHeader( 'Content-Type', 'text/html;charset=UTF-8' );
res.writeHead(200);
res.end(data);
});
}
/**
* \brief This function handles the connection to the clients.
*/
io.sockets.on('connection', function (webSocket) {
var tcpStream = new net.Stream;
tcpStream.setTimeout(0);
tcpStream.setEncoding("ascii");
webSocket.on('message', function (message) {
try
{
if(message.split(' ')[0] == 'CONNECT')
{
//connect to the given IRC server via TCP
var host = message.split(' ')[1].split(':')[0];
var port = message.split(' ')[1].split(':')[1];
console.log( 'connecting to '+host+':'+port+'…' );
tcpStream.destroy();
tcpStream.connect( port, host );
}
else
{
//forward message to the remote server via TCP
tcpStream.write(message);
}
}
catch (e)
{
webSocket.send(e);
}
});
/**
* \brief this function closes the connection to the IRC server when the connection to the client is closed.
*/
webSocket.on('disconnect', function () {
tcpStream.end();
});
/**
* \brief This function forwards error messages to the client
*/
tcpStream.addListener("error", function (error){
//forward error message to websocket
webSocket.send(error+"\r\n");
});
/**
* \brief This function handles the data received from the IRC server.
**/
tcpStream.addListener("data", function (data) {
//forward data to websocket
webSocket.send(data);
});
/**
* \brief This function notifies the client when the connection to the server is closed.
**/
tcpStream.addListener("close", function (){
webSocket.send("Server closed connection. You are offline. Use /connect to connect.");
});
});