今天群里一个同学找我要一个nodejs聊天室的demo。给他了一个简单的例子,顺便记录下:
准备工作(前提是已经装好了nodejs):mkdir nodejs-demo
cd nodejs-demo安装express : npm install express
安装socket.io : npm install socket.io
安装forever: npm install forever -g
安装完成之后会在目录下生成一个node_modules文件夹,把下面的server.js和client.html放到node_modules下。
下面是server.js:var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var history = new Array();
app.get('/', function(req, res) {
res.sendfile('client.html');
});
io.on('connection', function(socket) {
socket.on('chat message', function(msg) {
io.emit('chat message', msg);
addMsg(msg);
});
socket.on('login message', function(msg) {
socket.join('history room');
for (var i = 0;
i
i++) {
io.in('history room').emit('chat message', history[i]);
}
io.in('history room').emit('chat message', 'lyd__上面是最近的一些信息');
socket.leave('history room');
socket.join('chat room');
io.emit('chat message', msg);
addMsg(msg);
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
function addMsg(msg) {
history.push(msg);
if (history.length > 100)
history.shift();
};
下面是client.html:
demo* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 20px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; }
form button { width: 10%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px 5px 10px; }
登录
var socket = io();
var login = true;
var username = "";
var myDate = new Date();
$('form').submit(function() {
if (login) {
username = $('#m').val();
if (username.length == 0) {
alert("请输入用户名");
return false;
}
login = false;
socket.emit('login message', "lyd__" + username + '加入了聊天室 ' + myDate.getMonth() + "-" + myDate.getDate() + " " + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds());
$('#btn').html("发送");
} else {
socket.emit('chat message', username + "##" + $('#m').val());
}
$('#m').val('');
return false;
});
socket.on('chat message', function(msg) {
var item = msg.split("##", 2);
if (msg.indexOf('lyd__') == 0)
$('#messages').append('
' + msg.substr(5) + '');else if (msg.indexOf(username) == 0) {
$('#messages').append('
' + item[0] + ':');$('#messages').append('
' + item[1] + '');} else {
$('#messages').append('
' + item[0] + ':');$('#messages').append('
' + item[1] + '');}
});
运行:forever start server.js #启动 停止用stop
然后访问 192.168.1.8:3000,就可以聊天了
打赏
微信扫一扫,打赏作者吧~