聊天使用####

###########################################################################################################################################################

#

#

#

#

#

#

#

#

#

#

#

#

#

#

#

#

#

#

app.js

const express = require("express");
const app = express();
const { Server } = require("socket.io");
const io = new Server(3000, {
  cors: {
    origin: ["http://192.168.1.92:8080"],
  },
});

const userList = []; // 私聊数据表
const rooms = {}; // 群聊房间列表

io.on("connection", (socket) => {
  // 多人聊天精简版
  // 开始监听前端的socket请求连接(前端每次执行一次io()方法就就会发起一次socket请求)
  console.log("开始了");
  // 接收客户端发来的数据
  socket.on("joinRoom", (data) => {
    const { username, room } = JSON.parse(data);

    socket.join(room);

    if (!rooms[room]) {
      rooms[room] = [];
    }

    const user = { id: socket.id, username: username };
    rooms[room].push(user);
    console.log(`${username} joined room ${room}`);

    const userList = rooms[room].map((user) => user.username);
    io.to(room).emit("userList", JSON.stringify(userList));
  });

  socket.on("chat message", (data) => {
    const obj = JSON.parse(data);
    console.log("Received message:", obj.username, obj.mes);

    // 将消息发送给房间内的其他用户
    let roomUsers = rooms[obj.room];

    if (!Array.isArray(roomUsers)) {
      roomUsers = [];
    }

    roomUsers.forEach((user) => {
      if (user.id !== socket.id) {
        io.to(user.id).emit(
          "receiveMessage",
          JSON.stringify({ username: obj.username, mes: obj.mes })
        );
      }
    });
  });

  // 私人聊天版本
  // console.log('connection',socket.id);
  const username = socket.handshake.query.username;
  if (!username) return;

  const userInfo = userList.find((user) => user.username === username);
  if (userInfo) {
    userInfo.id = socket.id;
  } else {
    userList.push({
      id: socket.id,
      username,
    });

    // 监听用户断开连接事件,将用户从用户列表中移除
    socket.on("disconnect", () => {
      const index = userList.findIndex((user) => user.id === socket.id);
      if (index !== -1) {
        userList.splice(index, 1);
      }

      //多人聊天断开socket请求
      console.log("user disconnect --- 退出了了天", username);
      io.emit("tuichu", {
        msg: `用户${username}推出了聊天界面,选择某用户聊条吧...`,
      });

      Object.keys(rooms).forEach((room) => {
        const index = rooms[room].findIndex((user) => user.id === socket.id);
        if (index > -1) {
          rooms[room].splice(index, 1);
          const userList = rooms[room].map((user) => user.username);
          io.to(room).emit("userList", JSON.stringify(userList));
        }
      });
    });
  }
  // console.log(userList)
  io.emit("online", {
    userList,
  });

  socket.on("send", ({ fromUsername, targetId, msg }) => {
    // console.log(fromUsername,targetId,msg);
    // console.log(io.sockets.sockets.get(targetId));
    const targetSocket = io.sockets.sockets.get(targetId);
    const toUser = userList.find((user) => user.id === targetId);
    if (targetSocket) {
      targetSocket.emit("receive", {
        fromUsername,
        toUsername: toUser.username,
        msg,
        dateTime: new Date().getTime(),
      });
    } else {
      console.log("找不到目标用户的 socket");
      io.emit("duankai", {
        msg: "可能你或(对方)刷新了页面找不到目标用户,请重新选择目标用户,在进行交谈",
      });
    }
  });
});

app.listen(8000, (err) => {
  console.log("服务器启动成功");
});

home.vue






about.vue





chat.vue






你可能感兴趣的:(javascript)