我有一个小的node.js应用程序,它使用子域来缩短在网站路径中提交的链接(即请求http://a.example.com/google.com
使a.example.com
将来重定向到google.com
)。
我想使用socket.io来实现它,这样只要用户打开了重定向页面(store.html
),子域就会被停放。使用开放连接,我还可以向用户发送一个通知,告知该页面是由其他人访问的,等等。我通过观察socket.io断开连接事件来跟踪此store.html
连接的状态。
服务器:
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>
我遇到的问题是,如果我连接到同一浏览器中的子域,我会收到“传输错误”和断开连接事件,关闭套接字并触发从{{1}删除子域对象。当我在新标签中访问同一页面时,如何保持套接字打开?两者如何联系起来?
重申,这就是问题的发生方式:
link
http://link.example.com/google.com
,重定向到Google link.example.com
,收到指示空虚的回复