websocket - 实时聊天室

时间:2021-08-20 13:43:12
手把手教大家实现实时聊天室websocket - 实时聊天室websocket - 实时聊天室websocket - 实时聊天室websocket - 实时聊天室websocket - 实时聊天室

首先: 下载nodeJS然后通过express 搭建本地环境;
功能:实时侦听用户接入或断开并某一用户发送信息时其他用户能即是看见的聊天室
原理:先搭建服务器域,然后客户端访问该域时服务端返回各类信息;

注意:
服务端
    发送obj内信息给所有人(含自身)
    socket.emit( 'message' , obj );
    发送obj内信息给所有人(除自身)
    socket.broadcast.emit( 'system' , obj );

客户端
      通过服务端的emit的obj返回数据到前端
    socket.on( 'message' , function(obj){} )
以下是通过自身改良主要参考后的DEMO (包含发送时间 、断线重连提示、发送是否成功)
启动服务器:
    
    
    
  1. //找到对应的文件并安装所需的插件express / socket.io;
  2. e:
  3. cd websocket
  4. npm install
  5. node app.js

服务端
app.js
    
    
    
  1. var express = require('express');
  2. var path = require('path');
  3. var IO = require('socket.io');
  4. var router = express.Router();
  5. var app = express();
  6. var server = require('http').Server(app);
  7. app.use(express.static(path.join(__dirname, 'public')));
  8. app.set('views', path.join(__dirname, 'views'));
  9. app.set('view engine', 'hbs');
  10. // 创建socket服务
  11. var socketIO = IO(server);
  12. // 房间用户名单
  13. var roomInfo = {};
  14. socketIO.on('connection', function (socket) {
  15. // 获取请求建立socket连接的url
  16. // 如: http://localhost:3000/room/room_1, roomID为room_1
  17. var url = socket.request.headers.referer;
  18. var obj = { time:getTime() };
  19. var splited = url.split('/');
  20. obj.roomID = splited[splited.length - 1]; // 获取房间ID
  21. obj.user = '';
  22. socket.on('join', function (userName) {
  23. if(!userName){
  24. // 当输入空值时默认给时间戳为用户名
  25. var date = new Date();
  26. obj.user = +date;
  27. }else{
  28. obj.user = userName;
  29. }
  30. // 将用户昵称加入房间名单中
  31. if (!roomInfo[obj.roomID]) {
  32. roomInfo[obj.roomID] = [];
  33. }
  34. roomInfo[obj.roomID].push(obj.user);
  35. console.log(obj.roomInfo)
  36. socket.join(obj.roomID); // 加入房间
  37. // 通知房间内人员
  38. socketIO.to(obj.roomID).emit('sys', obj.user + '加入了房间'+ obj.time, roomInfo[obj.roomID]);
  39. console.log(obj.user + '加入了' + obj.roomID + '时间' + obj.time);
  40. });
  41. socket.on('leave', function () {
  42. socket.emit('disconnect');
  43. //socket.broadcast.emit('disconnect');与上效果一样,只是该方法是除去自己能看到;
  44. });
  45. //监听出退事件
  46. socket.on('disconnect', function () {
  47. // 从房间名单中移除
  48. var index = roomInfo[obj.roomID].indexOf(obj.user);
  49. if (index !== -1) {
  50. roomInfo[obj.roomID].splice(index, 1);
  51. }
  52. socket.leave(obj.roomID); // 退出房间
  53. socketIO.to(obj.roomID).emit('sys', obj.user + '退出了房间'+ obj.time, roomInfo[obj.roomID]);
  54. console.log(obj.user + '退出了' + obj.roomID + '时间' + obj.time);
  55. });
  56. // 接收用户消息,发送相应的房间
  57. socket.on('message', function (msg) {
  58. if(msg) obj.state = 1;
  59. // 验证如果用户不在房间内则不给发送
  60. if (roomInfo[obj.roomID].indexOf(obj.user) === -1) {
  61. return false;
  62. }
  63. socketIO.to(obj.roomID).emit('msg', obj, msg);
  64. });
  65. });
  66. // 指定webscoket的客户端的html文件
  67. router.get('/room/:roomID', function (req, res) {
  68. var roomID = req.params.roomID;
  69. // 渲染页面数据(见views/room.hbs)
  70. res.render('room', {
  71. roomID: roomID,
  72. users: roomInfo[roomID]
  73. });
  74. });
  75. app.use('/', router);
  76. server.listen(3000, function () {
  77. console.log('server listening on port 3000');
  78. });
  79. var getTime=function(){
  80. var date = new Date();
  81. return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDay() +
  82. ' ' + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
  83. }
客户端
index.html / room.hbs
   
   
   
  1. /*--room.hbs---*/
  2. <!DOCTYPE html>
  3. <html>
  4. <head lang="en">
  5. <meta charset="UTF-8">
  6. <title>{{roomID}}</title>
  7. <style>
  8. #msglog, #messageInput {
  9. border: 1px solid #ccc;
  10. width: 500px;
  11. height: 350px;
  12. overflow-y: auto;
  13. font-size: 14px;
  14. }
  15. #messageInput {
  16. height: 80px;
  17. }
  18. .message {
  19. line-height: 22px;
  20. }
  21. .message .user {
  22. padding-right: 5px;
  23. padding-left: 5px;
  24. color: brown;
  25. }
  26. .sysMsg {
  27. color: #c1bfbf;
  28. padding-right: 5px;
  29. padding-left: 5px;
  30. font-size: 12px;
  31. }
  32. #users {
  33. width: 490px;
  34. padding: 0 5px 5px;
  35. }
  36. .time{
  37. color:#999;
  38. float: right;
  39. }
  40. .success{
  41. color:white;
  42. padding:0px 2px;
  43. border-radius:2px;
  44. background-color:#45e945;
  45. }
  46. .fail{
  47. color:red;
  48. }
  49. </style>
  50. </head>
  51. <body>
  52. 昵称: <span id="userName"></span> <br/>
  53. 房间: {{roomID}} <br/>
  54. 当前在线人数: <span id="count">{{users.length}}</span> <br/>
  55. 在线用户: <div id="users">{{users}}</div>
  56. <div id="msglog">
  57. </div>
  58. <textarea name="message" id="messageInput"></textarea>
  59. <br/>
  60. 按Enter键发送
  61. <button id="joinOrLeave">退出房间</button>
  62. <script src="/socket.io/socket.io.js"></script>
  63. <script src="/js/jquery.js"></script>
  64. <script>
  65. $(function () {
  66. // ----------设置昵称-------------
  67. var userName = '';
  68. while ($('#userName').text().trim() === '') {
  69. userName = prompt("请设置你的昵称","");
  70. if(!userName){
  71. var date = new Date();
  72. userName = +date;
  73. }
  74. $('#userName').text(userName);
  75. }
  76. // ---------创建连接-----------
  77. var socket = io();
  78. // 加入房间
  79. socket.on('connect', function () {
  80. socket.emit('join', userName);
  81. id = socket.id;
  82. console.log(id);
  83. $('.disconnect').remove();
  84. });
  85. // 监听消息
  86. socket.on('msg', function (obj, msg) {
  87. var state = ( obj.state ) ? 'success' : 'fail';
  88. var message = '' +
  89. '<div class="message">' +
  90. ' <span class="user">' + obj.user + ': </span>' +
  91. ' <span class="msg">' + msg + '</span>' +
  92. ' <span class="time">' + obj.time + '</span>' +
  93. ' <span class="' + state + '">' + state + '</span>' +
  94. '</div>';
  95. $('#msglog').append(message);
  96. // 滚动条保持最下方
  97. $('#msglog').scrollTop($('#msglog')[0].scrollHeight);
  98. });
  99. // 监听系统消息
  100. socket.on('sys', function (sysMsg, users) {
  101. var message = '<div class="sysMsg">' + sysMsg + '</div>';
  102. $('#msglog').append(message);
  103. $('#count').text(users.length);
  104. $('#users').text(users);
  105. });
  106. // 断开连接
  107. socket.on('disconnect', (reason) => {
  108. $('body').prepend('<p class="disconnect" style="color:red"> DISCONNECT:'+reason+'<br/><span></span></p>');
  109. });
  110. //正在连接中
  111. socket.on('reconnecting', (attemptNumber) => {
  112. if(attemptNumber>20){
  113. socket.on('reconnect_failed', () => {
  114. alert('failed')
  115. });
  116. }
  117. $('.disconnect > span').empty().text('reconnecting...'+attemptNumber);
  118. });
  119. //成功重连
  120. socket.on('reconnection', (isLink) => {
  121. console.log(isLink)
  122. if(isLink){
  123. console.log('OK');
  124. //重连后判断是否还是同一窗口(具体还没实操);
  125. if(id == socket.id){
  126. console.log(id)
  127. }
  128. }
  129. });
  130. // 发送消息
  131. $('#messageInput').keydown(function (e) {
  132. if (e.which === 13) {
  133. e.preventDefault();
  134. var msg = $(this).val();
  135. $(this).val('');
  136. socket.send(msg);
  137. }
  138. });
  139. // 退出房间
  140. $('#joinOrLeave').click(function () {
  141. if ($(this).text() === '退出房间') {
  142. $(this).text('进入房间');
  143. socket.emit('leave');
  144. var msg = '你已经退出了房间,重新发言请点击"进入房间"';
  145. $('#msglog').append('<div class="sysMsg">'+msg+'</div>');
  146. } else {
  147. $(this).text('退出房间');
  148. socket.emit('join', userName);
  149. }
  150. });
  151. });
  152. </script>
  153. </body>
  154. </html>

    
    
    
  1. /*--- index.html ---*/
  2. <!DOCTYPE html>
  3. <html>
  4. <head lang="en">
  5. <meta charset="UTF-8">
  6. <title>demo</title>
  7. </head>
  8. <body>
  9. 欢迎您,骚年
  10. <div>
  11. <p>房间列表</p>
  12. <ul>
  13. <li id="room_1"><a href="/room/room_1" target="_blank">1号房间</a></li>
  14. <li id="room_2"><a href="/room/room_2" target="_blank">2号房间</a></li>
  15. <li id="room_3"><a href="/room/room_3" target="_blank">3号房间</a></li>
  16. <li id="room_4"><a href="/room/room_4" target="_blank">4号房间</a></li>
  17. <li id="room_5"><a href="/room/room_5" target="_blank">5号房间</a></li>
  18. <li id="room_6"><a href="/room/room_6" target="_blank">6号房间</a></li>
  19. <li id="room_7"><a href="/room/room_7" target="_blank">7号房间</a></li>
  20. <li id="room_8"><a href="/room/room_8" target="_blank">8号房间</a></li>
  21. <li id="room_9"><a href="/room/room_9" target="_blank">9号房间</a></li>
  22. <li id="room_10"><a href="/room/room_10" target="_blank">10号房间</a></li>
  23. </ul>
  24. </div>
  25. </body>
  26. </html>