首页 > 网站 > WEB开发 > 正文

node+express+socket.io制作一个聊天室功能

2024-04-27 14:15:18
字体:
来源:转载
供稿:网友

node+exPRess+socket.io制作一个聊天室功能

Posted on 2014-12-16 22:32 思思博士 阅读(...) 评论(...) 编辑 收藏

首先是下载包:

npm install express

npm install socket.io

建立文件:

服务器端代码:server.js

 1 var http=require("http"); 2 var express=require("express"); 3 var sio=require("socket.io"); 4  5 var app=express(); 6 app.use(express.static(__dirname+"/")); 7  8 var server=http.createServer(app); 9 app.get("/", function (req, res) {10     res.sendFile(__dirname+"/chart.html");11 });12 server.listen(1337,"127.0.0.1", function () {13    console.log("开始监听");14 });15 var io=sio.listen(server);16 var names=[];17 io.sockets.on("connection", function (socket) {18     socket.on("login", function (name) {19         for(var i=0;i<names.length;i++){20             if(names[i]==name){21                 socket.emit("duplicate");22                 return;23             }24         }25         names.push(name);26         io.sockets.emit("login",name);27         io.sockets.emit("sendClients",names);28     });29     socket.on("chat", function (data) {30         io.sockets.emit("chat",data);31     });32     socket.on("logout", function (name) {33         for(var i=0;i<names.length;i++){34             if(names[i]==name){35                 names.splice(i,1);36                 break;37             }38         }39         socket.broadcast.emit("logout",name);40         io.sockets.emit("sendClients",names);41     });42 });

静态页面 chart.html:

 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4     <meta charset="UTF-8"> 5     <title>Socket.IO聊天室</title> 6     <link rel="stylesheet" href="chart.CSS" /> 7     <script src="/socket.io/socket.io.js"></script> 8     <script type="text/javascript" src="chart.js"></script> 9 </head>10 <body onload="window_onload()">11 <h1>Socket.IO聊天室</h1>12 <div id="divContainer1">13     <table class="tbDlg" border="0" cellpadding="3" cellspacing="0" width="100%">14         <tr class="trDlg">15             <td class="tdDlg" width="5">16                 用户名:&nbsp;17                 <input id="tbxUsername" type="text" value="游客" size="20" />18                 <input id="btnLogin" type="button" value="登录" onclick="btnLogin_onclick();" />19                 <input id="btnLogout" type="button" value="退出" disabled onclick="btnLogout_onclick();" />20             </td>21         </tr>22     </table>23 </div>24 <div id="divLeft">25     <div id="divchat"></div>26     <div id="divContainer3">27         <table class="tbDlg" border="0" cellpadding="3" cellspacing="0" width="100%">28             <tr class="trDlg">29                 <td valign="top" class="tdDlg" nowrap>对话</td>30                 <td valign="top" class="tdDlg">31                     <textarea id="tbxMsg" cols="255" rows="5" style="width: 100%"></textarea>32                 </td>33                 <td valign="top" class="tdDlg">34                     <input id="btnSend" type="button" value="发送" disabled onclick="btnSend_onclick();" />35                 </td>36             </tr>37         </table>38     </div>39 </div>40 <div id="divRight">用户列表:</div>41 </body>42 </html>

静态css文件:

 1 h1{ 2     font-family: Arial,Helvetica,sans-serif; 3     font-weight: bold; 4     font-size: 14pt; 5     color: #006bb5; 6     background-color: #f0f0f0; 7     border-radius: 5px; 8     border: 1px solid #f0f0f0; 9     padding: 5px;10     margin: 0 0 18px 0;11 }12 div[id^=divContainer]{13     border: 0;14     margin: 10px 0;15     padding: 3px;16     background-color:#f0f0f0;17     border-radius: 5px;18 }19 div#divLeft{20     width: 85%;21     background-color:#f0f0f0;22     float: left;23 }24 div#divRight{25     width: 15%;26     background-color:white;27     float: right;28     font-weight: bold;29     font-size: 12px;30 }31 div#divchat{32     border: 0;33     margin: 10px 0;34     padding: 3px;35     background-color:#f0f0f0;36     border-radius: 5px;37     position: relative;38     height: 300px;39     overflow: auto;40     font-size: 12px;41 }42 table.tbDlg{43     font-family:Verdana,Helvetica,sans-serif;44     font-weight: normal;45     font-size: 12px;46     background-color: #f0f0f0;47 }48 tr.trDlg,td.tdDlg {49     background-color: #f0f0f0;50     font-size: 10px;51 }52  textarea{53      font-family: inherit;54      font-size: 10pt;55      border:1px solid #444;56      background-color:white;57      width: 100%;58 }59  input[type="button"]{60      font-family: inherit;61      border: 1px solid #808080;62      border-radius: 10px;63      margin: 1px;64      color: white;65      background-color:#81a0b5;66      width: 100px;67  }68 input[type="button"]:hover{69     margin: 1px;70     background-color: #006bb5;71 }72 input[type="button"]:active{73     margin: 1px;74     font-weight: bold;75     background-color:#006bb5;76 }77 input[type="button"]:focus{78     margin: 0;79     font-weight: bold;80     background-color:#006bb5;81 }

静态js文件

 1 var userName,//用户登录到socket.io聊天室中时所使用的用户名 2     socket,//与聊天服务器连接的socket端口对象 3     tbxUsername,//用户名文本框 4     tbxMsg,//对话文本框 5     divChat;//页面中显示消息区域 6 function window_onload(){ 7     divChat=document.getElementById("divchat"); 8     tbxUsername=document.getElementById("tbxUsername"); 9     tbxMsg=document.getElementById("tbxMsg");10     tbxUsername.focus();11     tbxUsername.select();12 }13 14 function AddMsg(msg){15     divChat.innerHTML+=msg+"<br>";16     if(divChat.scrollHeight>divChat.clientHeight)17         divChat.scrollTop=divChat.scrollHeight-divChat.clientHeight;18 }19 function btnLogin_onclick(){20     if(tbxUsername.value.trim()==""){21         alert("请输入用户名");22         return;23     }24     userName=tbxUsername.value.trim();25     socket=io.connect();26     socket.on("connect",function(){27         AddMsg("与聊天服务器的连接已建立.");28         socket.on("login", function (name) {29             AddMsg("欢迎用户"+name+"进入聊天室.");30         });31         socket.on("sendClients", function (names) {32             var divRight=document.getElementById("divRight");33             var str="";34             names.forEach(function (name) {35                 str+=name+"<br />";36             });37             divRight.innerHTML="用户列表<br />";38             divRight.innerHTML+=str;39         });40         socket.on("chat", function (data) {41             AddMsg(data.user+"说:"+data.msg);42         });43         socket.on("disconnect", function () {44             AddMsg("与聊天服务器的连接已断开.");45             document.getElementById("btnSend").diabled=true;46             document.getElementById("btnLogout").disabled=true;47             document.getElementById("btnLogin").disabled="";48             var divRight=document.getElementById("divRight");49             divRight.innerHTML="用户列表";50         });51         socket.on("logout", function (name) {52             AddMsg("用户"+name+"已退出聊天室.")53         });54         socket.on("duplicate", function () {55             alert("该用户名已被使用.");56             document.getElementById("btnSend").disabled=true;57             document.getElementById("btnLogout").disabled=true;58             document.getElementById("btnLogin").disabled="";59         });60     });61 62     socket.on("error", function (err) {63         AddMsg("与聊天服务器之间的链接发生错误.");64         socket.disconnect();65         socket.removeAllListeners("connect");66         io.sockets={};67     });68     socket.emit("login",userName);69     document.getElementById("btnSend").disabled="";70     document.getElementById("btnLogout").disabled="";71     document.getElementById("btnLogin").disabled=true;72 }73 74 function btnSend_onclick(){75     var msg=tbxMsg.value;76     if(msg.length>0){77         socket.emit("chat",{user:userName,msg:msg});78         tbxMsg.value="";79     }80 }81 function btnLogout_onclick(){82
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表