我对 NodeJS 开发很陌生。我在我的 express 应用程序中使用session.socket.io插件,但是当我在sessionSockets.on ('connection', . ..
这是整个app.js
:
var http = require('http'),
connect = require('express/node_modules/connect'),
express = require('express'),
app = express();
var cookieParser = express.cookieParser('Your secret key here'),
sessionStore = new connect.middleware.session.MemoryStore();
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(cookieParser);
app.use(express.session({
store: sessionStore
}));
app.use(app.router);
});
var server = http.createServer(app),
io = require('socket.io').listen(server);
var SessionSockets = require('session.socket.io'),
sessionSockets = new SessionSockets(io, sessionStore, cookieParser);
app.configure('development', function() {
app.use(express.errorHandler());
});
app.get('/', function(req, res) {
res.end("Welcome to the API server");
});
sessionSockets.on('connection', function(err, socket, session) {
console.log('-----------------------');
console.log(err.error);
console.log('-----------------------');
socket.emit('welcome', {
msg: 'You\'re now listening to the api.'
});
});
server.listen(app.get('port'), function() {
console.log("Express server listening on port " + app.get('port'));
});
客户端:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Express+SocketIO testing</title>
</head>
<body>
<div id="responses">
<h2>API responses:</h2>
<ul></ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io.connect('//localhost:3000');
// Welcome message
socket.on('welcome', function(data) {
var li = '<li>Server said: ' + data.msg + '</li>';
$('#responses ul').append(li);
});
});
</script>
</body>
</html>
包.json
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app"
},
"dependencies": {
"express": "3.0.3",
"socket.io":"*",
"session.socket.io":"*"
}
}
欢迎任何帮助或提示。谢谢你。