我正在尝试使用session.socket.io和rabbitMQ以及redis创建简单的聊天应用程序以进行会话存储。
app.js
var express = require('express'),
http = require('http'),
path = require('path'),
redis = require('redis'),
amqp = require('amqp'),
logger = require('morgan');
users = {};
var session = require('express-session');
var rabbitConn = amqp.createConnection({});
var chatExchange;
rabbitConn.on('ready', function () {
chatExchange = rabbitConn.exchange('chatExchange', { 'type': 'fanout' });
});
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);
io.set("transports", ["polling"]);
var RedisStore = require('connect-redis')(session),
rClient = redis.createClient(),
sessionStore = new RedisStore({ client: rClient });
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use(cookieParser());
app.use(session({ store: sessionStore, key: 'jsessionid', secret: 'your secret here', resave: true, saveUninitialized: true }));
var SessionSockets = require('session.socket.io');
var sessionSockets = new SessionSockets(io, sessionStore, cookieParser, 'jsessionid');
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
sessionSockets.on('connection', function (err, socket, session) {
console.log('sessionSockets connected');
socket.on('send message', function (data) {
io.sockets.emit('new message', { message: data, user: socket.nickName });
}).on('new user', function (data, callBack) {
console.log('new user called');
if (data in users) {
callBack(false);
} else {
socket.nickName = data;
users[socket.nickName] = socket;
updateUserName();
callBack(true);
}
}).on('disconnect', function () {
if (!socket.nickName) return;
delete users[socket.nickName];
updateUserName();
}).on('connectiontest', function (data) {
console.log(data);
});
function updateUserName() {
var test = {}
io.sockets.emit('usernames', Object.keys(users));
}
});
server.listen(3003);
的index.html
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head
<body>
<div id="nickWrap">
<p>Enter userName</p>
<p id="nickError"></p>
<form id="setNick">
<input size="35" id="nickName" />
<input type="submit" />
</form>
</div>
<div id="contentWrap">
<div id="chatWrap">
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message" />
<input type="submit" />
</form>
</div>
</div>
<div id="users"></div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var host = window.location.host;
console.log('host',host);
var socket = io.connect('http://' + host, {reconnect:false, 'try multiple transports':false});
var intervalID;
var reconnectCount = 0;
socket.on('connect', function () {
socket.emit('connectiontest', 'Hello server');
console.log('connected');
});
socket.on('connecting', function () {
console.log('connecting');
});
socket.on('disconnect', function () {
console.log('disconnect');
intervalID = setInterval(tryReconnect, 4000);
});
socket.on('connect_failed', function () {
console.log('connect_failed');
});
socket.on('error', function (err) {
console.log('error: ' + err);
});
socket.on('reconnect_failed', function () {
console.log('reconnect_failed');
});
socket.on('reconnect', function () {
console.log('reconnected ');
});
socket.on('reconnecting', function () {
console.log('reconnecting');
});
var tryReconnect = function () {
++reconnectCount;
if (reconnectCount == 5) {
clearInterval(intervalID);
}
console.log('Making a dummy http call to set jsessionid (before we do socket.io reconnect)');
$.ajax('/')
.success(function () {
console.log("http request succeeded");
//reconnect the socket AFTER we got jsessionid set
socket.socket.reconnect();
clearInterval(intervalID);
}).error(function (err) {
console.log("http request failed (probably server not up yet)");
});
};
var messageForm=$("#send-message");
var message=$("#message");
var chat=$("#chat");
var nickForm=$("#setNick");
var nickBox=$("#nickName");
var nickError=$("#nickError");
nickForm.submit(function(e){
e.preventDefault(e);
socket.emit('new user',nickBox.val(),function(data){
alert('hi');
if(data){
$("#nickWrap").hide();
$("#contentWrap").show();
}else{
nickError.html('User Name already taken');
}
});
});
messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message',message.val());
message.val('');
});
socket.on('new message',function(data){
chat.append(data.message+':->'+data.user+'</br>');
}).on('usernames',function(data){
console.log(data);
var html="";
for(var i=0;i<data.length;i++){
html+=data[i]+'</br>';
}
$("#users").html(html);
});
});
</script>
</body>
</html>