NodeJS和Socket.IO搭建聊天室应用

来源:互联网 发布:小众音乐软件 编辑:程序博客网 时间:2024/05/19 02:27

一个基于NodeJS和Socket.IO的简单的聊天室程序

index.html

<!DOCTYPE html><html><head><meta charset="utf-8"><link rel="stylesheet" href="css/reset.css" /><link rel="stylesheet" href="css/index.css" /><title></title></head><body><div class="login"><input type="text" id="username" placeholder="请填写你的用户名" /><input type="button" id="login_btn" value="登录" /><span>您还没有登录,不能开始聊天</span></div><!--login--><div class="box-1"><div class="content"><ul></ul></div><!--content--><div class="box-2"><input type="text" id="send_content" /><input type="button" id="send_btn" value="发送" disabled="true" class="active" /></div><!--box-2--></div><!--box-1--><div class="box-3"><h2>当前在线</h2><ul></ul></div><!--box-3--><script src="js/jquery-1.8.3.min.js"></script><script src="js/socket.io.js"></script><script>(function(){var w = window;w.CHAT = {username : null,socket : null,send_btn : $('#send_btn'),send_content : $('#send_content'),login_btn : $('#login_btn'),login_span : $('.login span'),ul : $('.content ul'),username_input : $('#username'),user_list : $('.box-3 ul'),start : function(){this.login_btn.on('click',function(){CHAT.login();})},init : function(){this.socket = io('ws://localhost:8080/');this.socket.on('connect',function(){console.log('已连接到服务器');})this.socket.on('message',function(data){CHAT.showMessage(data);})this.socket.on('login',function(data){CHAT.updateUserList(data.list);})this.socket.on('leave',function(data){console.log(data.username + '退出了聊天');CHAT.updateUserList(data.list);})this.send_btn.on('click',function(){CHAT.sendMessage();})this.send_content.keypress(function(event){if(event.which === 13){event.preventDefault();CHAT.sendMessage();}})},//登录login : function(){var username_val = $.trim(this.username_input.val());if(username_val !== ''){this.username = username_val;this.init();this.socket.emit('login',{username : username_val});this.login_span.html(username_val + '正在聊天');this.send_btn.removeClass('active').prop('disabled',false);this.login_btn.addClass('active').prop('disabled',true);}else{alert('请输入你的用户名');}},//发送消息sendMessage : function(){var content = $.trim(this.send_content.val());if(content === ''){alert('请先输入内容');return false;}this.socket.emit('message',{username : this.username,content : content});this.send_content.val('');},//显示消息showMessage : function(data){this.ul.append('<li><time>' + this.getTime() + '</time>' + data.username + '说:' + data.content + '</li>');//保持滚动条在最底部this.ul.scrollTop(this.ul.height());},//更新用户列表updateUserList : function(data){var username = data.split(','),str = '';for(var i=0,len=username.length;i<len;i++){str += '<li>' + username[i] + '</li>';}this.user_list.html(str);},//获取时间getTime : function(){var date = new Date(),str = date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日 ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();return str;}}CHAT.start();})()</script></body></html>
index.css

body{width:100%; font-size:12px;}.login{width:600px; height:40px; margin-top:100px; margin-left:100px;}.login #username{width:200px; height:38px; border:1px solid #505155; text-indent:10px;}.login #login_btn{width:98px; height:40px; background-color:#F02729; color:#FFF; border:0;}.login #login_btn.active{background-color:#838389;}.login span{margin-left:20px;}.box-1{width:600px; height:400px; border:1px solid #505155; margin-left:100px; margin-top:20px; float:left;}.box-1 .content{width:100%; height:339px; border-bottom:1px solid #505155; overflow:hidden;}.box-1 .content ul{width:90%; height:319px; margin-left:5%; margin-top:10px; overflow-x:hidden; overflow-y:auto; float:left;}.box-1 .content ul li:not(:nth-child(1)){margin-top:10px;}.box-1 .content ul li time{display:block; width:100%;}.box-1 .box-2{width:100%; height:60px;}.box-1 .box-2 #send_content{width:450px; height:40px; border:1px solid #505155; margin-top:9px; margin-left:20px; float:left; text-indent:10px;}.box-1 .box-2 #send_btn{width:98px; height:42px; margin-top:9px; margin-left:15px; float:left; background-color:#F02729; color:#FFF; border:0;}.box-1 .box-2 #send_btn.active{background-color:#838389;}.box-3{width:200px; height:400px; border:1px solid #505155; float:left; margin-top:20px; margin-left:15px; overflow-x:hidden; overflow-y:auto;}.box-3 h2{font-size:14px; text-align:center; height:40px; line-height:40px;}.box-3 ul{width:90%; margin-left:5%;}.box-3 ul li{width:100%; height:25px; line-height:25px;}
server.js

var http = require('http'),io = require('C:/Users/Administrator/AppData/Roaming/npm/node_modules/socket.io');var server = http.createServer(function(req,res){res.writeHead(200,{'Content-Type' : 'text/html'});})server.listen(8080);var socket = io.listen(server);//在线用户var users = [];socket.on('connection',function(client){console.log('已经连接到客户端');client.on('login',function(data){client.name = data.username;if(users.indexOf(data.username) === -1){users.push(data.username);socket.emit('login',{list : users.join()});}else{console.log('该用户已经在线');}})client.on('message',function(data){socket.emit('message',{username : data.username,content : data.content});})client.on('disconnect',function(){if(client.name !== 'undefined'){console.log(client.name + '已经断开连接');var index = users.indexOf(client.name);if(index !== -1){//删除该用户users.splice(index,1);socket.emit('leave',{username : client.name,list : users.join()});}}})})
注意:Node环境下执行server.js,在浏览器中打开客户端即可登录聊天(请先NPM安装Socket.IO包)

参考链接:http://www.plhwin.com/2014/05/28/nodejs-socketio/

0 0