I have a little node.js app that uses subdomains to shorten links which are submitted in the site's path (i.e. requesting http://a.example.com/google.com
makes it so a.example.com
redirects to google.com
in the future).
I wanted to use socket.io to make it so the subdomain was parked only as long as a user had the redirection page (store.html
) open. Using the open connection, I could also send the user a notification that the page was accessed by someone else, etc. I am tracking the status of this store.html
connection by watching for the socket.io disconnection event.
server:
var app = require('express')()
, fs = require ('fs')
, http = require('http').createServer(app)
, io = require('socket.io')(http)
, links = {};
app.get('/favicon.ico',function(r,s){});
app.get('/',function(req,res) {
var subd=req.subdomains[0];
if (!subd) {
res.sendfile(__dirname + '/public/index.html');
} else {
if (link[subd]) {
res.redirect(link[subd].URL);
} else {
res.send('nothing saved here');
}
}
});
app.get('*',function(req,res) {
var subd=req.subdomains[0];
if (!subd) {
res.send('invalid URL');
} else if (link[subd]) {
res.send('subdomain in use');
} else {
var URL=req.originalUrl.substring(1);
link[subd]={ URL: (/^\w+:\/\//.test(URL) ? URL : (/^\w+\.\w+/.test(URL) ? http://'+URL : 'http://google.com')) };
res.sendfile(__dirname+'/public/store.html');
}
});
io.on('connection', function(socket) {
socket.on('subd',function(subd) {
socket.subd=subd;
link[subd].socket=socket;
socket.emit('content',link[subd].URL);
});
socket.on('disconnect',function() {
delete link[socket.subd];
});
});
store.html:
<html>
<body>
<span>HTML / Link</span>
<div id="content"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var subd=location.hostname.split('.').shift()'
var socket = io.connect('http://example.com');
socket.on('connect', function() {
socket.emit('subd', subd);
});
socket.on('content',function(content) {
document.getElementById('content').innerHTML='<a href="'+content+'">'+content+'</a>';
});
socket.on('disconnect',function(reason){
alert(reason);
});
</script>
</body>
</html>
The problem I'm running into is that if I connect to the subdomain within the same browser, I get a "transport error" and disconnection event, closing the socket and triggering the deletion of the subdomain from the link
object. How can I keep the socket open when I access the same page in a new tab? How are the two linked?
restated, this is how the problem happens:
http://link.example.com/google.com
link.example.com
, redirects to google link.example.com
, receive response indicating emptiness