用 express-ws 和 socket.io 分别构建 Nodejs websocket 服务器端有区别吗
用 express-ws 和 socket.io 分别构建 Nodejs websocket 服务器端有区别吗
express-ws 构建的服务,可以用第三方 client 链接发送数据
const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
const morgan = require('morgan');
const compression = require('compression');
const serveStatic = require('serve-static');
const basicAuth = require('basic-auth-connect');
const user = process.env.USER;
const pass = process.env.PASS;
let connects = [];
app.set('port', process.env.PORT || 8080);
if (user && pass) {
app.use(basicAuth(user, pass));
}
app.use(morgan('dev'));
app.use(compression());
app.use(serveStatic(`${__dirname}/public`));
app.ws('/', (ws, req) => {
connects.push(ws);
ws.on('message', message => {
console.log('Received -', message);
connects.forEach(socket => {
socket.send(message);
});
});
ws.on('close', () => {
connects = connects.filter(conn => {
return (conn === ws) ? false : true;
});
});
});
app.listen(app.get('port'), () => {
console.log('Server listening on port %s', app.get('port'));
});
socket.io 构建的服务第三方 client 连接不上,但是 demo 可以发送数据
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')( http);
var port = process.env.PORT || 3000;
app.get(’/’, function(req, res){
res.sendFile(__dirname + ‘/index.html’);
});
io.on(‘connection’, function(socket){
console.log(‘connection’);
socket.on(‘chat message’, function(msg){
console.log(‘chat message’, msg);
io.emit(‘chat message’, msg);
});
});
http.listen(port, function(){
console.log(‘listening on *:’ + port);
});
刚刚接触,没理解问题出现在哪里
纯粹测试
纯 websocket 相当于就是一个 socket,只要是个 websocket 的客户端就能用
在Node.js中,express-ws
和 socket.io
都是用于构建WebSocket服务器的库,但它们在使用方式、功能集和适用场景上有显著区别。
express-ws
express-ws
是将WebSocket功能添加到Express应用的一个中间件。它允许你在现有的Express路由和中间件的基础上添加WebSocket支持。
const express = require('express');
const expressWs = require('express-ws')(express());
app.ws('/echo', (ws, req) => {
ws.on('message', (msg) => {
console.log(msg);
ws.send(`You said: ${msg}`);
});
});
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
socket.io
socket.io
是一个更高级的库,它不仅支持WebSocket,还包括其他传输方式(如长轮询),以确保在不同环境和网络条件下都能提供可靠的实时通信。它提供了更丰富的API,如事件发射、房间管理等。
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('message', (msg) => {
console.log(msg);
socket.emit('message', `You said: ${msg}`);
});
});
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
总之,express-ws
更适合在已有Express应用上添加WebSocket支持,而socket.io
提供了更全面的实时通信功能。