Socket.IO + Express实现的跨浏览器、子域的聊天室

 

实例中用到了(实例在Windows XP下运行):Node.jsSocket.IOExpress.jsjadestylus

 

先在hosts文件中添加两行规则,关于两个子域的:sub1.localhost、sub2.localhost

使用socket.io

   1: var exp = require('express');
   2: var app = exp.createServer();
   3:  
   4: global.socket = require('socket.io').listen(app);
   5: global.socket.set('log level', 1);
   6: global.socket.set('transports', [ 'websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);

加载配置,创建子域的应用

   1: app.use(exp.vhost('sub1.' + global.host, require('./subdomains/sub1')));
   2: app.use(exp.vhost('sub2.' + global.host, require('./subdomains/sub2')));
   3:  
   4: require('./app/config')(app, exp);
   5: require('./app/server/router')(app);
   6: require('./app/server/modules/chat-socket');

chat-socket.js模块

   1: module.exports = function() {
   2:         
   3:     global.socket.of('/chat').on('connection', function(socket) { 
   4:        //todo 
   5:     });
   6: }();

前台页面使用socket.io.js建立连接

   1: socket = io.connect('/chat');
   2: socket.on('status', function (connections) {
   3:     
   4: });
   5: socket.on('user-ready', function (data) {
   6:     
   7: });
   8: socket.on('user-message', function (data) {
   9:     
  10: });
  11:  
  12: socket.on('user-disconnected', function (data) {
  13:     
  14: });
  15:  
  16: //向后台发送消息
  17: socket.emit('user-ready', {name : 'xxx'});

 

运行完整的示例node app.js即可,下载示例源码>>

 

本文参考:

1、http://www.quietless.com/kitchen/building-a-node-js-chat-application-and-sharing-socket-io-across-multiple-subdomains/

2、creating-a-basic-site-with-node-and-express

posted @ 2012-07-26 22:27  meteoric_cry  阅读(6476)  评论(1编辑  收藏  举报