webSocket 聊天室 node.js 版

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

后端代码

src 同级目录下建 server:

 webSocket 聊天室 node.js 版_第1张图片

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 = '';
}

完整代码:





你可能感兴趣的:(node.js,websocket,网络协议)