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'));
});
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);
});
刚刚接触,没理解问题出现在哪里
1
x1911 2019-07-18 16:50:00 +08:00
这个是用于什么环境下呢
|
3
pastgift 2019-08-07 23:09:36 +08:00
纯 websocket 相当于就是一个 socket,只要是个 websocket 的客户端就能用
|