欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

node.js結(jié)合webSocket實(shí)現(xiàn)聊天室

 更新時(shí)間:2023年08月20日 15:11:43   作者:牧羊狼的狼  
于Node.js和WebSocket的聊天室,主要包括前端頁(yè)面,主要是用戶(hù)操作的頁(yè)面,還包括后臺(tái)數(shù)據(jù)通信以及邏輯處理,具有一定的參考價(jià)值,感興趣的可以了解一下

全局安裝vue腳手架  npm install @vue/cli -g
創(chuàng)建 vue3 + ts 腳手架  vue create vue3-chatroom

后端代碼

src 同級(jí)目錄下建 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(`收到了前端發(fā)來(lái)的消息: ${data}`);
    io.emit("sendToClient", data);
  })
  socket.on('disconnect', () => {
    console.log('斷開(kāi)連接');
  });
});
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(`收到了后端發(fā)來(lái)的數(shù)據(jù):${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">發(fā) 送</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') || '匿名用戶(hù)'
var socket = io('ws://localhost:3000')
socket.on("sendToClient", data => {
  console.log(`收到了后端發(fā)來(lái)的數(shù)據(jù):${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>

到此這篇關(guān)于node.js結(jié)合webSocket實(shí)現(xiàn)聊天室 的文章就介紹到這了,更多相關(guān)node.js webSocket聊天室 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • nodejs的壓縮文件模塊archiver用法示例

    nodejs的壓縮文件模塊archiver用法示例

    這篇文章主要介紹了nodejs的壓縮文件模塊archiver用法,結(jié)合實(shí)例形式分析了nodejs使用archiver模塊實(shí)現(xiàn)文件壓縮操作的步驟與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2017-01-01
  • node.js中ws模塊創(chuàng)建服務(wù)端和客戶(hù)端,網(wǎng)頁(yè)WebSocket客戶(hù)端

    node.js中ws模塊創(chuàng)建服務(wù)端和客戶(hù)端,網(wǎng)頁(yè)WebSocket客戶(hù)端

    今天小編就為大家分享一篇關(guān)于node.js中ws模塊創(chuàng)建服務(wù)端和客戶(hù)端,網(wǎng)頁(yè)WebSocket客戶(hù)端,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-03-03
  • nvm介紹、安裝、報(bào)錯(cuò)處理及使用詳細(xì)步驟

    nvm介紹、安裝、報(bào)錯(cuò)處理及使用詳細(xì)步驟

    所謂nvm就是一個(gè)可以讓你在同一臺(tái)機(jī)器上安裝和切換不同版本node的工具,下面這篇文章主要給大家介紹了關(guān)于nvm介紹、安裝、報(bào)錯(cuò)處理及使用的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2022-09-09
  • Node.js API詳解之 assert模塊用法實(shí)例分析

    Node.js API詳解之 assert模塊用法實(shí)例分析

    這篇文章主要介紹了Node.js API詳解之 assert模塊用法,結(jié)合實(shí)例形式分析了Node.js API中assert模塊基本函數(shù)、功能、用法及操作注意事項(xiàng),需要的朋友可以參考下
    2020-05-05
  • nodejs如何獲取指定路徑下所有的文件夾名或類(lèi)型

    nodejs如何獲取指定路徑下所有的文件夾名或類(lèi)型

    這篇文章主要介紹了nodejs如何獲取指定路徑下所有的文件夾名或類(lèi)型,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • 在NodeJs中使用node-schedule增加定時(shí)器任務(wù)的方法

    在NodeJs中使用node-schedule增加定時(shí)器任務(wù)的方法

    這篇文章主要介紹了從零開(kāi)始在NodeJs中使用node-schedule增加定時(shí)器任務(wù)的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-06-06
  • node使用Mongoose類(lèi)庫(kù)實(shí)現(xiàn)簡(jiǎn)單的增刪改查

    node使用Mongoose類(lèi)庫(kù)實(shí)現(xiàn)簡(jiǎn)單的增刪改查

    Mongoose是在nodejs環(huán)境中對(duì)MongoDB數(shù)據(jù)庫(kù)操作的封裝,這篇文章主要介紹了node使用Mongoose類(lèi)庫(kù)實(shí)現(xiàn)簡(jiǎn)單的增刪改查,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-11-11
  • Node.js的模塊化機(jī)制和Buffer對(duì)象詳解

    Node.js的模塊化機(jī)制和Buffer對(duì)象詳解

    這篇文章主要為大家詳細(xì)介紹了Node.js的模塊化機(jī)制和Buffer對(duì)象,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2022-02-02
  • npm更新命令更新最新版本的實(shí)現(xiàn)方式

    npm更新命令更新最新版本的實(shí)現(xiàn)方式

    這篇文章主要介紹了npm更新命令更新最新版本的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • node.js實(shí)現(xiàn)爬蟲(chóng)教程

    node.js實(shí)現(xiàn)爬蟲(chóng)教程

    這篇文章主要為大家介紹了node.js基礎(chǔ)模塊http、網(wǎng)頁(yè)分析工具cherrio實(shí)現(xiàn)爬蟲(chóng)的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-03-03

最新評(píng)論