最近在研究直播 須要作一個webIM 聊天的功能 找到了這個socket.io css
從 http://www.plhwin.com/2014/05/28/nodejs-socketio/ 和 socket.io官網 https://socket.io/get-started/chat/ 學到不少 , 下面的代碼也是基於這兩篇文章,感謝 他們讓我學到新的知識html
搭建聊天室 首先須要一個用nodeJs 搭建的servernode
第一步:jquery
在任意一個位置建立一個 文件夾 ,一會要將js、html等文件放在其中 我建立的是chat文件夾。web
第二步:express
要把運行node的環境搭好,上node官網 下載一個,安裝上 就能夠了,npm
一切準備就緒後打開 node.js command prompt 也就是那個黑的框框 ,進入到你當前的工做路徑, 個人是D:\my\chat後端
第三步:瀏覽器
在你剛剛建立的目錄下 建立一個index.js,搭建node server,代碼以下:服務器
var express = require('express'); var app = express(); var http = require('http').Server(app); app.get('/', function(req, res){ res.send("hello"); }); http.listen(3001, function(){ console.log('listening on *:3001'); });
完成 以後再 node command 裏運行 node index.js ,會提醒讓安裝 express 模塊 再 運行 npm install --save express 便可 ,安裝成功以後 在運行 node index.js 會出現以下界面 :
證實成功,在瀏覽器運行 http://127.0.0.1:3001/ 會出現 hello
第四步:建立index.html ,搭建聊天頁面
代碼以下:
<!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } .send { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } .send input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } .send button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } .user{width: 100%; background-color:#c2c2c2; margin-bottom: 5px;min-height: 40px; line-height: 30px} .user div,.service div{float: left; font-size: 18px; } .user span,.service span{float: left; font-size: 16px; } .service{width: 100%; background-color:#c4c4c4; margin-bottom: 5px;min-height: 40px; line-height: 30px} </style> </head> <body> <div id="chatbox" > <div style="background:#3d3d3d;height: 28px; width: 100%;font-size:12px;"> <div style="line-height: 28px;color:#fff;"> <span style="text-align:left;margin-left:10px;">多人聊天室</span> <span style="float:right; margin-right:10px;"><span id="showusername"></span> </div> </div> <ul id="messages"> <div id="onlinecount" style="background:#EFEFF4; font-size:12px; margin-top:10px; margin-left:10px; color:#666;"> </div> </ul> <div class="send"> <input id="m" autocomplete="off" /><button onclick="chat.submit()">Send</button> </div> <script src="/socket.io/socket.io.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script src="client.js"></script> </body> </html>
第五步:完善index.js 加入socket.io模塊,會遇到安裝模塊的提示 ,安裝便可, 完整代碼以下:
var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http);
//在html 頁面引入css,js 須要放在public 目錄下 ,express.static 來設置靜態文件如:圖片, CSS, JavaScript等 app.use(express.static('public')); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); //在線用戶 var onlineUsers = {}; //當前在線人數 var onlineCount = 0; io.on('connection', function(socket){ // console.log('a user connected'); //監聽新用戶加入 socket.on('login', function(obj){ //將新加入用戶的惟一標識看成socket的名稱,後面退出的時候會用到 socket.name = obj.username; //檢查在線列表,若是不在裏面就加入 if(!onlineUsers.hasOwnProperty(obj.username)) { onlineUsers[obj.username] = obj.username; //在線人數+1 onlineCount++; } //向全部客戶端廣播用戶加入 io.emit('login', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj}); console.log(obj.username+'加入了聊天室'); }); //監聽用戶退出 socket.on('disconnect', function(){ //將退出的用戶從在線列表中刪除 if(onlineUsers.hasOwnProperty(socket.name)) { //退出用戶的信息 var obj = { username:onlineUsers[socket.name]}; //刪除 delete onlineUsers[socket.name]; //在線人數-1 onlineCount--; //向全部客戶端廣播用戶退出 io.emit('logout', {onlineUsers:onlineUsers, onlineCount:onlineCount, user:obj}); console.log(obj.username+'退出了聊天室'); } }); socket.on('message', function(msg){ io.emit('message', msg); }); }); io.emit('some event', { for: 'everyone' }); http.listen(3000, function(){ console.log('listening on *:3000'); });
第六步:是寫client.js ,這裏面主要是有發送消息,監聽發送消息、更新系統消息等,這個代碼是是http://www.plhwin.com/2014/05/28/nodejs-socketio/ 這個寫的 ,謝謝大神的提供:
var chat = { msgObj:document.getElementById("messages"), username:null, socket:null, //讓瀏覽器滾動條保持在最低部 scrollToBottom:function(){ window.scrollTo(0, this.msgObj.clientHeight); }, //提交聊天消息內容 submit:function(){ var content = document.getElementById("m").value; if(content != ''){ var obj = { username: this.username, content: content }; chat.socket.emit('message', obj); document.getElementById("m").value = ''; } }, init:function(){ /* 客戶端根據時間和隨機數生成uid,這樣使得聊天室用戶名稱能夠重複。 實際項目中,若是是須要用戶登陸,那麼直接採用用戶的uid來作標識就能夠 */ this.username = this.genUid(); document.getElementById("showusername").innerHTML = this.username; document.getElementById("messages").style.minHeight = (this.screenheight - document.body.clientHeight + this.msgObj.clientHeight) + "px"; this.scrollToBottom(); //鏈接websocket後端服務器 this.socket = io.connect('ws://127.0.0.1:3000'); //告訴服務器端有用戶登陸 this.socket.emit('login', { username:this.username}); //監聽新用戶登陸 this.socket.on('login', function(o){ chat.updateSysMsg(o, 'login'); }); //監聽用戶退出 this.socket.on('logout', function(o){ chat.updateSysMsg(o, 'logout'); }); //監聽消息發送 this.socket.on('message', function(obj){ var isme = (obj.username == chat.username) ? true : false; var contentDiv = '<div>'+obj.content+'</div>'; var usernameDiv = '<span>'+obj.username+'說</span>'; var section = document.createElement('section'); if(isme){ section.className = 'user'; section.innerHTML = usernameDiv + contentDiv ; } else { section.className = 'service'; section.innerHTML = usernameDiv + contentDiv; } chat.msgObj.appendChild(section); chat.scrollToBottom(); }); }, //更新系統消息,本例中在用戶加入、退出的時候調用 updateSysMsg:function(o, action){ //當前在線用戶列表 var onlineUsers = o.onlineUsers; //當前在線人數 var onlineCount = o.onlineCount; //新加入用戶的信息 var user = o.user; //更新在線人數 var userhtml = ''; var separator = ''; for(key in onlineUsers) { if(onlineUsers.hasOwnProperty(key)){ userhtml += separator+onlineUsers[key]; separator = '、'; } } document.getElementById("onlinecount").innerHTML = '當前共有 '+onlineCount+' 人在線,在線列表:'+userhtml; //添加系統消息 var html = ''; html += '<div class="msg-system">'; html += user.username; html += (action == 'login') ? ' 加入了聊天室' : ' 退出了聊天室'; html += '</div>'; var section = document.createElement('section'); section.className = 'system J-mjrlinkWrap J-cutMsg'; section.innerHTML = html; this.msgObj.appendChild(section); this.scrollToBottom(); }, genUid:function(){ return new Date().getTime()+""+Math.floor(Math.random()*899+100); } }; window.chat = chat; chat.init();
這樣就基本完成了聊天的搭建,在瀏覽器運行 http://127.0.0.1:8084/index.html就能夠聊天了,效果入下:
這樣聊天室就基本完成了
謝謝 大神的代碼,讓我學習不少 http://www.plhwin.com/2014/05/28/nodejs-socketio/ 和 socket.io官網 https://socket.io/get-started/chat/