Node.js+socket.io在线聊天室
Node.js+socket.io实现在线聊天室,照着这个教程做的,稍加改动即可实现。
Node.js:0.10.31
Express:3.*
创建工程chat:
添加几个文件,工程结构如下
代码:
package.json:
{ "name": "application-name", "version": "0.0.1", "private": true, "scripts": { "start": "node app.js" }, "dependencies": { "express": "3.16.7", "ejs": "*", "socket.io":"*" } }app.js:
//引入程序包 var express = require('express') , path = require('path') , app = express() , server = require('http').createServer(app) , io = require('socket.io').listen(server); //设置日志级别 io.set('log level', 1); //WebSocket连接监听 io.on('connection', function (socket) { socket.emit('open');//通知客户端已连接 // 打印握手信息 // console.log(socket.handshake); // 构造客户端对象 var client = { socket:socket, name:false, color:getColor() } // 对message事件的监听 socket.on('message', function(msg){ var obj = {time:getTime(),color:client.color}; // 判断是不是第一次连接,以第一条消息作为用户名 if(!client.name){ client.name = msg; obj['text']=client.name; obj['author']='System'; obj['type']='welcome'; console.log(client.name + ' login'); //返回欢迎语 socket.emit('system',obj); //广播新用户已登陆 socket.broadcast.emit('system',obj); }else{ //如果不是第一次的连接,正常的聊天消息 obj['text']=msg; obj['author']=client.name; obj['type']='message'; console.log(client.name + ' say: ' + msg); // 返回消息(可以省略) socket.emit('message',obj); // 广播向其他用户发消息 socket.broadcast.emit('message',obj); } }); //监听出退事件 socket.on('disconnect', function () { var obj = { time:getTime(), color:client.color, author:'System', text:client.name, type:'disconnect' }; // 广播用户已退出 socket.broadcast.emit('system',obj); console.log(client.name + 'Disconnect'); }); }); //express基本配置 app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler()); }); // 指定webscoket的客户端的html文件 app.get('/', function(req, res){ res.sendfile('chat/views/chat.html'); }); server.listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); }); var getTime=function(){ var date = new Date(); return date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(); } var getColor=function(){ var colors = ['aliceblue','antiquewhite','aqua','aquamarine','pink','red','green', 'orange','blue','blueviolet','brown','burlywood','cadetblue']; return colors[Math.round(Math.random() * 10000 % colors.length)]; }chat.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Socket.io - Simple chat</title> <link rel="stylesheet" type="text/css" href="css/main.css"> <script src="http://cdn.staticfile.org/jquery/2.1.1-rc2/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script src="javascripts/chat.js"></script> </head> <body> <h1>Socket.io - Simple chat room</h1> <div> <span id="status">Connecting...</span> <input type="text" id="input"/> </div> <div id="content"></div> </body> </html>chat.js:
$(function () { var content = $('#content'); var status = $('#status'); var input = $('#input'); var myName = false; //建立websocket连接,本机测试可以用localhost socket = io.connect('http://192.168.37.151:3000'); //收到server的连接确认 socket.on('open',function(){ status.text('Choose a name:'); }); //监听system事件,判断welcome或者disconnect,打印系统消息信息 socket.on('system',function(json){ var p = ''; if (json.type === 'welcome'){ if(myName==json.text) status.text(myName + ': ').css('color', json.color); p = '<p style="background:'+json.color+'">system @ '+ json.time+ ' : Welcome ' + json.text +'</p>'; }else if(json.type == 'disconnect'){ p = '<p style="background:'+json.color+'">system @ '+ json.time+ ' : Bye ' + json.text +'</p>'; } content.prepend(p); }); //监听message事件,打印消息信息 socket.on('message',function(json){ var p = '<p><span style="color:'+json.color+';">' + json.author+'</span> @ '+ json.time+ ' : '+json.text+'</p>'; content.prepend(p); }); //通过“回车”提交聊天信息 input.keydown(function(e) { if (e.keyCode === 13) { var msg = $(this).val(); if (!msg) return; socket.send(msg); $(this).val(''); if (myName === false) { myName = msg; } } }); });main.css:
* {padding:0px; margin:0px;} body{font-family:tahoma; font-size:12px;margin:10px;} p {line-height:18px;padding:2px;} div {width:500px;} #content { padding:5px; background:#ddd; border-radius:5px; border:1px solid #CCC; margin-top:10px; } #input { border-radius:2px; border:1px solid #ccc; margin-top:10px; padding:5px; width:380px; } #status { width:100px; display:block; float:left; margin-top:15px; }在电脑1,浏览器访问http://192.168.37.151:3000/(http://localhost:3000,这里是为了在内网测试)
输入名字,dss,回车:
在电脑2,访问同样地址,名字输入,dss2,回车
这是电脑1上:
聊几句吧:
电脑2关闭页面后电脑1:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。