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);
});
刚刚接触,没理解问题出现在哪里
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.