node.js结合webSocket实现聊天室

 更新时间:2023年08月20日 15:11:43   作者:牧羊狼的狼  
于Node.js和WebSocket的聊天室,主要包括前端页面,主要是用户操作的页面,还包括后台数据通信以及逻辑处理,具有一定的参考价值,感兴趣的可以了解一下

全局安装vue脚手架  npm install @vue/cli -g
创建 vue3 + ts 脚手架  vue create vue3-chatroom

后端代码

src 同级目录下建 server:

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server, { cors: true })
io.on('connection', (socket) => {
  console.log('socket 已连接');
  socket.on('sendToServer', data => {
    console.log(`收到了前端发来的消息: ${data}`);
    io.emit("sendToClient", data);
  })
  socket.on('disconnect', () => {
    console.log('断开连接');
  });
});
server.listen(3000, () => {
  console.log('listening on *:3000');
});

前端代码

核心代码:

import io from 'socket.io-client'
var socket = io('ws://localhost:3000')
socket.on("sendToClient", data => {
  console.log(`收到了后端发来的数据:${data}`);
  records.value.push(JSON.parse(data))
})
const sendMessage = () => {
  if (!message.value.trim()) return
  const record: IRecord = reactive({
    message: message.value,
    nickname,
    userId: new Date().getTime() + '',
    color: '',
    sendTime: getYMDHMS(new Date().getTime())
  })
  socket.emit('sendToServer', JSON.stringify(record));
  message.value = '';
}

完整代码:

<template>
  <div class="chat-room">
    <div class="nav"></div>
    <div class="main">
      <div class="title">
        <span>图灵聊天室({{ userCount }})</span>
      </div>
      <div class="content" ref="recordsContent">
        <div v-for="(itm, inx) in records" :key="inx">
          <div
            class="item"
            :class="[itm.nickname === nickname ? 'item' : 'item-other']"
          >
            <div class="info">[ {{ itm.nickname }}:{{ itm.sendTime }} ]</div>
            <span class="message">{{ itm.message }}</span>
          </div>
        </div>
      </div>
      <div class="input-box">
        <div class="text">
          <textarea :rows="8" v-model="message" @keydown="onKeydown"></textarea>
        </div>
        <div class="opt">
          <button ghost @click="sendMessage">发 送</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import io from 'socket.io-client'
import { reactive, ref } from 'vue'
interface IRecord {
  nickname: string,
  userId: string,
  color: string,
  message: string,
  sendTime: string
}
const userCount = ref(2)
const records = ref<IRecord[]>([])
const message = ref('')
const nickname = localStorage.getItem('username') || '匿名用户'
var socket = io('ws://localhost:3000')
socket.on("sendToClient", data => {
  console.log(`收到了后端发来的数据:${data}`);
  records.value.push(JSON.parse(data))
})
const sendMessage = () => {
  if (!message.value.trim()) return
  const record: IRecord = reactive({
    message: message.value,
    nickname,
    userId: new Date().getTime() + '',
    color: '',
    sendTime: getYMDHMS(new Date().getTime())
  })
  socket.emit('sendToServer', JSON.stringify(record));
  message.value = '';
}
const onKeydown = (event: any) => {
  if (event.keyCode === 13) {
    sendMessage()
  }
}
function getYMDHMS(timestamp:number) {
  let time = new Date(timestamp)
  let year = time.getFullYear()
  let month:any = time.getMonth() + 1
  let date:any = time.getDate()
  let hours:any = time.getHours()
  let minute:any = time.getMinutes()
  let second:any = time.getSeconds()
  if (month < 10) { month = '0' + month }
  if (date < 10) { date = '0' + date }
  if (hours < 10) { hours = '0' + hours }
  if (minute < 10) { minute = '0' + minute }
  if (second < 10) { second = '0' + second }
  return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}
</script>
<style scoped lang="scss">
.chat-room {
  margin: 0px auto;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: row;
  border: 1px solid #ccc;
  overflow: hidden;
  .nav {
    width: 66px;
    background: #363636;
    flex-shrink: 0;
  }
  .main {
    display: flex;
    background: #efefef;
    flex: 1;
    width: 0;
    display: flex;
    flex-direction: column;
    .title {
      height: 60px;
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 700;
      padding-left: 20px;
      border-bottom: 1px solid #c3c3c3;
      flex-shrink: 0;
    }
    .content {
      flex: 1;
      height: 0px;
      position: relative;
      overflow-y: auto;
      padding: 10px;
      .item {
        text-align: right;
        .info {
          font-size: 14px;
          color: #666;
        }
        .message {
          font-size: 18px;
          background-color: rgba(110, 89, 228, 0.579);
          margin: 10px;
          padding: 8px 12px;
          border-radius: 8px;
          display: inline-block;
          color: #333;
        }
      }
      .item-other {
        text-align: left;
        .message {
          background-color: rgb(218, 197, 112);
        }
      }
    }
    .input-box {
      height: 230px;
      border-top: 1px solid #c3c3c3;
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      .text {
        flex: 1;
        textarea {
          width: 94%;
          height: 160px;
          font-size: 16px;
          resize: none;
          border: none;
          padding: 8px 24px;
          background: #efefef;
          &:focus {
            outline: none;
          }
          &:focus-visible {
            outline: none;
          }
        }
      }
      .opt {
        height: 60px;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding-right: 20px;
      }
    }
  }
}
</style>

到此这篇关于node.js结合webSocket实现聊天室 的文章就介绍到这了,更多相关node.js webSocket聊天室 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • nodejs的压缩文件模块archiver用法示例

    nodejs的压缩文件模块archiver用法示例

    这篇文章主要介绍了nodejs的压缩文件模块archiver用法,结合实例形式分析了nodejs使用archiver模块实现文件压缩操作的步骤与相关注意事项,需要的朋友可以参考下
    2017-01-01
  • node.js中ws模块创建服务端和客户端,网页WebSocket客户端

    node.js中ws模块创建服务端和客户端,网页WebSocket客户端

    今天小编就为大家分享一篇关于node.js中ws模块创建服务端和客户端,网页WebSocket客户端,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-03-03
  • nvm介绍、安装、报错处理及使用详细步骤

    nvm介绍、安装、报错处理及使用详细步骤

    所谓nvm就是一个可以让你在同一台机器上安装和切换不同版本node的工具,下面这篇文章主要给大家介绍了关于nvm介绍、安装、报错处理及使用的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2022-09-09
  • Node.js API详解之 assert模块用法实例分析

    Node.js API详解之 assert模块用法实例分析

    这篇文章主要介绍了Node.js API详解之 assert模块用法,结合实例形式分析了Node.js API中assert模块基本函数、功能、用法及操作注意事项,需要的朋友可以参考下
    2020-05-05
  • nodejs如何获取指定路径下所有的文件夹名或类型

    nodejs如何获取指定路径下所有的文件夹名或类型

    这篇文章主要介绍了nodejs如何获取指定路径下所有的文件夹名或类型,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • 在NodeJs中使用node-schedule增加定时器任务的方法

    在NodeJs中使用node-schedule增加定时器任务的方法

    这篇文章主要介绍了从零开始在NodeJs中使用node-schedule增加定时器任务的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-06-06
  • node使用Mongoose类库实现简单的增删改查

    node使用Mongoose类库实现简单的增删改查

    Mongoose是在nodejs环境中对MongoDB数据库操作的封装,这篇文章主要介绍了node使用Mongoose类库实现简单的增删改查,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • Node.js的模块化机制和Buffer对象详解

    Node.js的模块化机制和Buffer对象详解

    这篇文章主要为大家详细介绍了Node.js的模块化机制和Buffer对象,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-02-02
  • npm更新命令更新最新版本的实现方式

    npm更新命令更新最新版本的实现方式

    这篇文章主要介绍了npm更新命令更新最新版本的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • node.js实现爬虫教程

    node.js实现爬虫教程

    这篇文章主要为大家介绍了node.js基础模块http、网页分析工具cherrio实现爬虫的相关资料,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-03-03

最新评论