用uniapp 及socket.io做一个简单聊天app 2

在这里只有群聊,二个好友聊天,可以认为是建了一个二人的群聊。

php 复制代码
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors'); // 引入 cors 中间件

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*", // 允许所有来源
    methods: ["GET", "POST"]
  }
});

// 使用 cors 中间件
app.use(cors());

const port = 3000;
const groups = {};

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

  // 用户加入群组
  socket.on('joinGroup', ({ groupName, userName }) => {
    socket.join(groupName);
    groups[socket.id] = { groupName, userName };
    socket.to(groupName).emit('message', `${userName} has joined the group`);
    console.log(`${userName} joined group ${groupName}`);
  });

  // 发送消息
  socket.on('sendMessage', ({ groupName, message, userName }) => {
    io.to(groupName).emit('message', `${userName}: ${message}`);
    console.log(`Message sent to ${groupName}: ${userName}: ${message}`);
  });

  // 踢人
  socket.on('kickUser', ({ groupName, userName }) => {
    for (let id in groups) {
      if (groups[id].userName === userName && groups[id].groupName === groupName) {
        io.sockets.sockets.get(id).leave(groupName);
        io.to(groupName).emit('message', `${userName} has been kicked from the group`);
        console.log(`${userName} was kicked from group ${groupName}`);
        break;
      }
    }
  });

  // 用户断开连接
  socket.on('disconnect', () => {
    if (groups[socket.id]) {
      const { groupName, userName } = groups[socket.id];
      socket.to(groupName).emit('message', `${userName} has left the group`);
      delete groups[socket.id];
      console.log(`${userName} left group ${groupName}`);
    }
  });
});

server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

uniapp的界面

php 复制代码
<template>
  <view class="container">
    <view>
      <input v-model="userName" placeholder="用户名"/>
      <input v-model="groupName" placeholder="群名"/>
      <button @click="joinGroup">加入群</button>
      <button @click="kickUser">踢人</button>
    </view>
    <view>
      <view id="messages">
        <view v-for="(msg, index) in messages" :key="index">{{ msg }}</view>
      </view>
      <input v-model="message" placeholder="输入聊天"/>
      <button @click="sendMessage">聊天</button>
    </view>
  </view>
</template>

<script>
import io from 'socket.io-client';

export default {
  data() {
    return {
      socket: null,
      userName: 'wanghaibin',
      groupName: 'wanghaibin',
      message: '',
      messages: []
    };
  },
  onLoad() {
    this.socket = io('http://127.0.0.1:3000');
    this.socket.on('message', (msg) => {
      this.messages.push(msg);
    });
  },
  methods: {
    joinGroup() {
      this.socket.emit('joinGroup', { groupName: this.groupName, userName: this.userName });
    },
    sendMessage() {
      if (this.message.trim() !== '') {
        this.socket.emit('sendMessage', { groupName: this.groupName, message: this.message, userName: this.userName });
        this.message = '';
      }
    },
    kickUser() {
      const userNameToKick = prompt('Enter the username to kick:');
      this.socket.emit('kickUser', { groupName: this.groupName, userName: userNameToKick });
    }
  }
};
</script>

<style>
.container {
  padding: 20px;
}
#messages {
  height: 300px;
  overflow-y: scroll;
  border: 1px solid #ccc;
  margin-bottom: 10px;
}
input {
  display: block;
  margin: 10px 0;
}
button {
  display: block;
  margin: 10px 0;
}
</style>

运行效果:

相关推荐
Moment3 分钟前
MinIO已死,MinIO万岁
前端·后端·github
无双_Joney7 分钟前
心路散文 - 转职遇到AI浪潮,AIGC时刻人的价值是什么?
前端·后端·架构
有意义27 分钟前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
小怪点点34 分钟前
vue3使用
前端·vue.js
Bigger1 小时前
CSS 这些年都经历了什么?一次看懂 CSS 的演化史
前端·css·前端工程化
DevUI团队1 小时前
🚀 【Angular】MateChat V20.2.2版本发布,新增8+组件,欢迎体验~
前端·javascript·人工智能
嚴寒1 小时前
前端配环境配到崩溃?这个一键脚手架让我少掉了一把头发
前端·react.js·架构
DevUI团队2 小时前
🚀 MateChat V1.11.0 震撼发布!新增工具按钮栏组件及体验问题修复,欢迎体验~
前端·javascript·人工智能
看晴天了2 小时前
新框架electronbun项目入门指南,解决electron体积大的难题,Electrobun:Electron 的轻量级革命 —— 12MB 应用 +
前端·架构
哇哇哇哇2 小时前
跨域:原因、解决方案CORS、JSONP、proxy、iframe(自用)
前端