为什么在路由更改时触发socket.on('disconnect')?

时间:2019-12-15 15:29:10

标签: express vue.js socket.io vue-router

我正在尝试通过创建一个聊天应用程序来第一次学习VueJS和Socket.IO。 问题是当我使用路由器显示另一个组件并且不知道为什么时,使用socket.io的快速服务器始终会收到 disconnected 事件。

这是正常现象吗?我该如何解决?

server.js

const app = require("express")();
const http = require("http").Server(app);
const cors = require('cors');
const bodyParser = require('body-parser');
const io = require("socket.io")(http);

const users = [];
const rooms = [];

io.on('connection', socket => {
    console.log('New connection');
    console.log('Total clients :', io.engine.clientsCount);

    // Connect
    socket.on('newUser', username => {
        console.log(`${username} connected.`);
        socket.username = username;
        users.push(socket);

        io.emit('userOnline', {users: users.map(u => u.username)});
    });

    socket.on('userJoinedRoom', room => {
        console.log(`${socket.username} connected to room ${room}.`);
        socket.room = room;
        socket.join(room);

        // echo to client he's connected
        socket.emit('updateChat', `SERVER : You joined room ${room}.`);

        // echo to room that a person has connected to their room
        socket.broadcast.to(room).emit('updateChat', `SERVER : ${socket.username} joined this room.`);
    });

    // Disconnect
    socket.on('disconnect', () => {
        console.log(`${socket.username} has left.`);
        console.log('Total clients :', io.engine.clientsCount);
        users.splice(users.indexOf(socket), 1);

        // echo globally that this client has left
        socket.broadcast.emit('updateChat', `SERVER : ${socket.username} has disconnected.`);
        socket.leave(socket.room);

        io.emit('userLeft', {users: users.map(u => u.username)});
    })
});

http.listen(2564, () => {
    console.log('Listening on port', 2564)
});

index.ts

const routes = [
  {
    path: "/",
    name: "home",
    component: Home
  },
  {
    path: "/room/:name",
    name: "room",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ "../views/Room.vue")
  }
];

Room.vue

<template>
  <div>
    <p v-for="message in messagesList" :key="message">
      {{ message }}
    </p>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { SocketInstance } from "@/main";

@Component
export default class Room extends Vue {
  messagesList: string[] = [];

  mounted() {
    SocketInstance.emit("userJoinedRoom", this.$route.params.name);  
    this.listen();
  }

  private listen() {
    SocketInstance.on("updateChat", (data: any) => {
      this.messagesList.push(data);
    });
  }
}
</script>

通常,我应该得到“服务器:xxx已加入此会议室”。但是这是将我重定向到 Room.vue 组件(服务器日志)时得到的:

    testUser has left. 
    Total clients : 0 
    New connection 
    Total clients : 1 
    undefined connected to room testRoom.

0 个答案:

没有答案