1 Star 0 Fork 4

木易杨/nodejs-socketio-chatroom

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
server.js 1.21 KB
一键复制 编辑 原始数据 按行查看 历史
nut77 提交于 2018-07-18 16:36 . update server.js
const http = require('http');
const express = require('express');
const socketIo = require('socket.io');
const favicon = require('serve-favicon');
const app = express();
const server = http.createServer(app); // <==> const server = app.listen(2000);
server.listen(2000);
app.use(favicon(__dirname + '/favicon.ico'));
app.use(express.static(__dirname + '/public'));
app.get('/index', (req, res) => {
res.sendfile(__dirname + '/views/index.html');
});
const io = socketIo.listen(server);
var users = []; // 用户列表
io.sockets.on('connection', socket => {
socket.on('disconnect', () => {
console.log(`服务端:客户端断开连接。`);
});
// 自定义事件
socket.on('login', user => {
if (-1 != users.indexOf(user)) {
socket.emit('duplicateUser');
return false;
}
users.push(user);
io.sockets.emit('login', user);
io.sockets.emit('chgUserlist', users);
});
socket.on('chat', data => {
io.sockets.emit('chat', data);
});
socket.on('exit', user => {
users.splice(users.indexOf(user), 1);
socket.broadcast.emit('exit', user);
socket.broadcast.emit('chgUserlist', users);
});
});
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
NodeJS
1
https://gitee.com/yangzhigang1998/nodejs-socketio-chatroom.git
[email protected]:yangzhigang1998/nodejs-socketio-chatroom.git
yangzhigang1998
nodejs-socketio-chatroom
nodejs-socketio-chatroom
master

搜索帮助