这是我尝试进行以下工作的尝试:
-
快递:4.14
-
socket.io:1.5
-
护照(使用会话):0.3
-
redis:2.6(非常快速的数据结构来处理会话;但您也可以使用其他类似 MongoDB。但是,我鼓励您将它用于会话数据 + MongoDB 来存储其他持久性数据,如用户)
由于您可能还想添加一些 API 请求,我们还将使用 http 包让 HTTP 和 Web 套接字在同一个端口上工作。
server.js
以下摘录仅包含设置先前技术所需的所有内容。你可以看到我在我的一个项目here中使用的完整的 server.js 版本。
import http from 'http';
import express from 'express';
import passport from 'passport';
import { createClient as createRedisClient } from 'redis';
import connectRedis from 'connect-redis';
import Socketio from 'socket.io';
// Your own socket handler file, it's optional. Explained below.
import socketConnectionHandler from './sockets';
// Configuration about your Redis session data structure.
const redisClient = createRedisClient();
const RedisStore = connectRedis(Session);
const dbSession = new RedisStore({
client: redisClient,
host: 'localhost',
port: 27017,
prefix: 'stackoverflow_',
disableTTL: true
});
// Let's configure Express to use our Redis storage to handle
// sessions as well. You'll probably want Express to handle your
// sessions as well and share the same storage as your socket.io
// does (i.e. for handling AJAX logins).
const session = Session({
resave: true,
saveUninitialized: true,
key: 'SID', // this will be used for the session cookie identifier
secret: 'secret key',
store: dbSession
});
app.use(session);
// Let's initialize passport by using their middlewares, which do
//everything pretty much automatically. (you have to configure login
// / register strategies on your own though (see reference 1)
app.use(passport.initialize());
app.use(passport.session());
// Socket.IO
const io = Socketio(server);
io.use((socket, next) => {
session(socket.handshake, {}, next);
});
io.on('connection', socketConnectionHandler);
// socket.io is ready; remember that ^this^ variable is just the
// name that we gave to our own socket.io handler file (explained
// just after this).
// Start server. This will start both socket.io and our optional
// AJAX API in the given port.
const port = 3000; // Move this onto an environment variable,
// it'll look more professional.
server.listen(port);
console.info(`? API listening on port ${port}`);
console.info(`? Socket listening on port ${port}`);
sockets/index.js
我们的socketConnectionHandler,我只是不喜欢将所有内容都放在 server.js 中(即使你完全可以),特别是因为这个文件很快就会包含大量代码。
export default function connectionHandler(socket) {
const userId = socket.handshake.session.passport &&
socket.handshake.session.passport.user;
// If the user is not logged in, you might find ^this^
// socket.handshake.session.passport variable undefined.
// Give the user a warm welcome.
console.info(`⚡︎ New connection: ${userId}`);
socket.emit('Grettings', `Grettings ${userId}`);
// Handle disconnection.
socket.on('disconnect', () => {
if (process.env.NODE_ENV !== 'production') {
console.info(`⚡︎ Disconnection: ${userId}`);
}
});
}
附加材料(客户):
只是 JavaScript socket.io 客户端的一个非常基本的版本:
import io from 'socket.io-client';
const socketPath = '/socket.io'; // <- Default path.
// But you could configure your server
// to something like /api/socket.io
const socket = io.connect('localhost:3000', { path: socketPath });
socket.on('connect', () => {
console.info('Connected');
socket.on('Grettings', (data) => {
console.info(`Server gretting: ${data}`);
});
});
socket.on('connect_error', (error) => {
console.error(`Connection error: ${error}`);
});
参考资料:
我只是无法在代码中引用,所以我把它移到了这里。
1:如何设置您的 Passport 策略:https://scotch.io/tutorials/easy-node-authentication-setup-and-local#handling-signupregistration