蚂蚁前端课程简易聊天室

思路

浏览器(cilent)

  1. 发起登录操作
    1. 获取用户名和密码
    2. 发送信息到服务器端验证
    3. 事件绑定到按钮上
  2. 发送信息
    1. 获取到输入框的内容
    2. socket.emit(‘sendMessage’, msg)
    3. 自己的聊天界面 $(text) 里新增消息记录
    4. 广播到其他的浏览器端中
  3. online
    1. 服务端发送当前已登录的用户
    2. 拿到登录用户后,显示在左边的好友列表
  4. 获取历史记录
    1. socket.emi(‘getHistory’)
    2. 服务器端返回保存的历史记录
    3. 拿到历史记录后渲染聊天框中

服务器端(server)

  1. 通过中间件的形式 io.use 验证账号密码是否为空
  2. 在 connected 事件里获取到浏览器的 socket
    1. socket.on(‘sendMessage’)
    2. 拼装 Message 对象,包含消息内容 content,发送时间,发送人
    3. 将信息对象 push 到 history 中
    4. 通过广播发生消息
  3. 增加获取历史记录的接口
    1. socket.on(‘getHistory’) 将历史记录返回浏览器
  4. 触发 online 事件
    1. io 监听 connected 和 disconnect 事件后
    2. 将保存在全局的 sockets 通过 socket.emit(‘online’) 发送浏览器
    3. disconnect 事件,delete name,然后再发送

      具体结构

      服务端JS

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      const http = require('http');
      const express = require('express');
      const socketIO = require('socket.io').Server;

      const app = new express();
      const server = http.createServer(app);
      const io = new socketIO(server);

      const sockets = {};
      const historys = [];

      app.use(express.static('./web'));

      io.use((socket, next) => {
      console.log('a client incoming');
      const name = socket.handshake.query.name;
      const password = socket.handshake.query.password;
      if (!name) {
      console.log('拒绝连接:没有账户名');
      next(new Error('empty'));
      return;
      }
      if (password !== '123') {
      console.log('拒绝连接:密码错误');
      next(new Error('error'));
      return;
      }
      next();
      });

      io.on('connection', (socket) => {
      console.log('a user connected');

      const name = socket.handshake.query.name;
      sockets[name] = socket;
      socket.on('sendMessage', (content) => {
      console.log('receive a message', name, content);
      const message = {
      time: Date.now(),
      sender: name,
      content
      };
      historys.push(message);
      socket.broadcast.emit('receiveMessage', message);
      });
      socket.on('getHistory', (fn) => {
      fn(historys);
      });
      socket.on('disconnect', (reason) => {
      delete sockets[name];
      console.log('sa user disconnect:', name, reason);
      io.sockets.emit('online', Object.keys(sockets));
      });
      io.sockets.emit('online', Object.keys(sockets));
      });

      server.listen(3000);

      网页文件(web文件夹与xerver.js同级)

      客户端JS

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      // 快捷选择方法
      function $(query) {
      return document.querySelector(query)
      }

      // 登录模块
      var login = $('#login');
      // 聊天室模块
      var chatroom = $('#chatroom');
      // 保存连接对象,后面需要用到
      var socket = null;

      // 登录方法
      function onLoginFunction() {
      var inputNameValue = $('#inputName').value;
      var inputPwdValue = $('#inputPwd').value;
      socket = io({
      query: {
      name: inputNameValue,
      password: inputPwdValue
      },
      reconnection: false,
      });

      socket.on('connect', () => {
      login.setAttribute("class", "login disappear");
      setTimeout(() => {
      chatroom.setAttribute("style", "display: flex");
      }, 1500);

      socket.emit('getHistory', (data) => {
      console.log('history', data);
      var textSection = $('#text-section');
      textSection.innerHTML = data.map((value) => {
      if (value.sender == inputNameValue) {
      return (
      `<div class="msg msg-me">
      <label>${value.sender}</label>
      <div class="msg-txt">${value.content}</div>
      </div>`
      );
      }
      return (
      `<div class="msg">
      <label>${value.sender}</label>
      <div class="msg-txt">${value.content}</div>
      </div>`
      );
      }).join('');
      });

      socket.on('receiveMessage', (message) => {
      var textSection = $('#text-section');
      textSection.innerHTML += (
      `<div class="msg">
      <label>${message.sender}</label>
      <div class="msg-txt">${message.content}</div>
      </div>`
      );
      });

      // socket.on('online', (onlines) => {
      // console.log('onlines', onlines);
      // var friendSection = $('#friend-box');
      // friendSection.innerHTML = onlines.map(name => {
      // return `<p class="friend-profile">${name}</p>`;
      // }).join('');
      // });
      });

      socket.on('connect_error', (e) => {
      console.log('connect_error', e);
      if (e && e.message === 'error') {
      alert('密码错误,请检查');
      return;
      }
      alert('链接失败,请检查服务器地址');
      });
      var login = document.querySelector('#login')
      const chatRoom = document.querySelector('#chatRoom')
      login.style.top = '-100%'
      chatRoom.style.top = '0'
      }

      var loginbutton = $('.login-button');
      loginbutton.addEventListener('click', onLoginFunction);

      // 发送
      function onSendFunction() {
      var textSection = $('#text-section');
      var msg = $('.input-area').value;
      if (!msg) {
      alert('请输入内容');
      return;
      }
      $('.input-area').value = '';
      var inputNameValue = $('#inputName').value;
      socket.emit('sendMessage', msg);
      textSection.innerHTML += `<div class="msg msg-me">
      <label>${inputNameValue}</label>
      <div class="msg-txt">${msg}</div>
      </div>`
      }
      var sendBtn = $('.send-button');
      sendBtn.addEventListener('click', onSendFunction);

      总HTML

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      <html>
      <head>
      <meta charset="UTF-8">
      <meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Room</title>
      <script type="text/javascript" src="/socket.io/socket.io.js"></script>
      <link rel="stylesheet" type="text/css" href="index.css">
      </head>
      <body>
      <div class="login" id="login">
      <p class="login-title">登录</p>
      <div class="content usrName">
      <span>账户名</span>
      <input type="text" id="inputName">
      </div>
      <div class="content usrPwd">
      <span>密码</span>
      <input type="password" id="inputPwd">
      </div>
      <button class="login-button">确认</button>
      </div>
      <div class="wrap chatRoom" id="chatroom">
      <div class="left" id="friend-box">
      <div class="li">A</div>
      <div class="li">B</div>
      <div class="li">C</div>
      <div class="li">D</div>
      </div>
      <div class="right">
      <div class="title">Room</div>

      <div class="msg-wrap" id="text-section">
      <div class="msg">
      <img class="avatar" src="./me.png">
      <div class="msg-txt">hello</div>
      </div>
      </div>

      <div class="input-wrap">
      <input class="input-area">
      <button class="send-button">发送</button>
      </div>
      </div>
      </div>
      <script src="index.js"></script>
      </body>
      </html>

      CSS

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      141
      142
      143
      144
      145
      146
      147
      148
      149
      150
      151
      152
      153
      154
      155
      156
      157
      158
      159
      160
      161
      162
      163
      164
      html, body{
      height: 100%;
      }

      body {
      margin: 0;
      background:
      linear-gradient(63deg, rgb(233, 233, 233) 23%, transparent 23%) 7px 0,
      linear-gradient(63deg, transparent 74%, rgb(233, 233, 233) 78%),
      linear-gradient(63deg, transparent 34%, rgb(233, 233, 233) 38%, rgb(233, 233, 233) 58%, transparent 62%),#444;
      background-size: 16px 48px;
      }

      .login {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 50px;
      border: none;
      border-radius: 10px;
      background-color: #ffffff;
      opacity:0.95;
      box-shadow: 5px 5px 10px #494848, -5px -5px 10px #ffffff;
      transition: all 0.5s ease;
      }

      .login-title {
      text-align: center;
      font-size: 20px;
      }

      .content {
      padding: 10px 0;
      display: flex;
      }

      .content span{
      display: block;
      width: 50px;
      margin-right: 10px;
      border: none;
      border-radius: 3px;
      background-color: #e6e6e6;
      box-shadow: 5px 5px 10px #bbbbbb, -5px -5px 10px #ffffff;

      }

      .content input{
      width: 200px;
      border-radius: 3px;
      border: none;
      background-color: #e6e6e6;
      box-shadow: 5px 5px 10px #bbbbbb, -5px -5px 10px #ffffff;

      }

      .login-button {
      display: block;
      margin: 0 auto;
      padding: 5px 10px;
      border: none;
      border-radius: 20px;
      font-size: 18px;
      cursor: pointer;
      background-color: #e6e6e6;
      box-shadow: 5px 5px 10px #bbbbbb, -5px -5px 10px #ffffff;
      }

      .send-button {
      display: block;
      margin: 0 auto;
      padding: 5px 10px;
      border: none;
      border-radius: 20px;
      font-size: 18px;
      cursor: pointer;
      background-color: #e6e6e6;
      box-shadow: 5px 5px 10px #bbbbbb, -5px -5px 10px #ffffff;
      }

      .chatRoom {
      transition: all 0.5s ease;
      }

      .wrap {
      display: flex;
      height: 100%;
      /* position: relative; */
      top: -100%;
      }

      .left {
      width:150px;
      background-color: rgb(29, 49, 28);
      color: #ffffff;
      border-bottom: 1px solid rgb(70, 70, 70);
      padding: 5px;
      }

      .li {
      border-bottom: 1px solid #111;
      padding: 5px 10px;
      }

      .right {
      flex: 1;
      background-color: antiquewhite;
      display: flex;
      flex-direction: column;
      }

      .title {
      text-align: center;
      border-bottom: 1px solid #999;
      }

      .input-wrap {
      display: flex;
      padding: 5px;
      border-top: 1px solid #999;
      }

      .input-area {
      flex: 1;
      margin: 0 10px;
      }

      .msg-wrap {
      overflow: scroll;
      padding: 10px;
      flex: 1;
      }

      .msg {
      flex: 1;
      display: flex;
      align-items: center;
      }

      .msg-me {
      flex-direction: row-reverse;
      }

      .msg-me .msg-txt{
      background-color: rgb(81, 108, 81);
      }

      .avatar {
      width: 50px;
      height: 50px;
      border-radius:50%;
      margin: 0 5px;
      }

      .msg-txt {
      display: inline-block;
      background-color: #fff;
      padding: 5px;
      border-radius: 5px;
      height: fit-content;
      background-color: #e6e6e6;
      box-shadow: 5px 5px 10px #bbbbbb, -5px -5px 10px #ffffff;
      }

      仅作简单了解前端的练习

---------------THEEND---------------