我为我的问题找到了解决方案,所以我将其添加为我自己问题的答案。我提到了 socket.io 聊天应用程序,它很有用,但没有完整的文档。对于某些功能,我们需要通过源代码。我使用会话来识别套接字和 http 请求以及每个客户端。我将粘贴我发现可行的代码。
var io = require('socket.io');
var express = require('express');
var http = require('http');
var fs = require('fs');
var connect = require('connect');
var cookie = require("cookie");
var app = express();
var server = http.createServer(app)
var parseCookie = connect.utils.parseCookie;
var parseSignedCookie = connect.utils.parseSignedCookie;
var MemoryStore = connect.session.MemoryStore;
var sessionStore = new MemoryStore();
app.configure(function () {
app.use(express.bodyParser());
app.use(express.cookieParser('somesuperspecialsecrethere'));
app.use(express.session({
key: 'express.sid',
store: sessionStore
}));
});
app.get('/', function(req, res){
fs.readFile(__dirname + '/index.html',
function(err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
console.log("SessionID from http: "+req.sessionID);
setTimeout(function () { //this is for simulating a time taking task
var sock_id = io.sockets.sockets[req.sessionID];
io.sockets.sockets[sock_id].emit("getmessage","my mmmmmmmmmmmmmessssssage");
}, 5000);
});
});
GLOBAL.sio = io.listen(server);
server.listen(3000);
sio.sockets.on('connection', function (socket) {
var hs = socket.handshake;
socket.on('clientMessage', function(data) {
console.log("Message from client: "+ data.message);
io.sockets.sockets[hs.sessionID] = socket.id;
});
});
sio.set('authorization', function (data, accept) {
if (!data.headers.cookie) {
return accept('Session cookie required.', false);
}
data.cookie = cookie.parse(data.headers.cookie);
data.cookie = parseSignedCookie(data.cookie['express.sid'], 'somesuperspecialsecrethere');
data.sessionID = data.cookie;
console.log('Session Id from socket: ' + data.sessionID);
sessionStore.get(data.sessionID, function(err, session){
if (err) {
return accept('Error in session store.', false);
} else if (!session) {
return accept('Session not found.', false);
}
// success! we're authenticated with a known session.
data.session = session;
return accept(null, true);
});
<html>
<head>
<title>express WebSocket chat</title>
<script src="http://10.3.0.52:3000/socket.io/socket.io.js"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>
</head>
<body>
<script src="http://10.3.0.52:3000/socket.io/socket.io.js"></script>
<script type="text/javascript">
var sio = io.connect('http://10.3.0.52:3000');
sio.socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
sio.on('connect', function (){
console.info('successfully established a working connection ');
});
sio.on('getmessage', function(data) {
console.log(data);
});
</script>
<input type="text" name="message" id="message">
<input type="button" name="send" id="send" value="Send">
</body>
</html>