websocket 当socket.io用户在Angular 8中更改路由时,关闭www.example.com连接

u59ebvdq  于 2022-11-11  发布在  Angular
关注(0)|答案(2)|浏览(188)

Socket.io 用户尝试关闭选项卡或窗口时,www.example.com关闭连接,但当用户导航到同一Angular 应用程序中的其他路线时,它不会关闭连接,在这种情况下,断开连接事件将不会触发。服务器端:

io.on('connection', function (socket) {
    console.log('a user connected');

    socket.on('disconnect', function () {
        console.log('user disconnected');
    });
});

socket.disconnect()方法将不起作用。
我正在尝试使用CanDisconnect路由防护,但不知道如何使用它来关闭连接。
服务器端:

// dependencies
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

//importing routes
var loginRouter = require('./routes/loginRoutes');
var chatRouter = require('./routes/chatRoutes');
app.use('/', loginRouter); // applying routes to the app
app.use('/', chatRouter); // applying routes to the app

// starting the server
http.listen(3000, function(){
    console.log('server is listening on port '+PORT);
});

// socket.io ===================================

io_public = io.of('/public');  // namespace public
io_public.on('connection', function(socket){

    socket.on('adduser', function(username){
        socket.username = username;
        socket.room = 'public'; //assign default public room
        socket.join(socket.room);

        socket.emit('server', 'you have connected to a public room');
        socket.broadcast.to('public').emit('server',socket.username + ' has connected to this room');    
});

socket.on('disconnect', function(){
  socket.broadcast.to('public').emit('server',socket.username + ' has left the room');
  socket.leave(socket.room);
});

});

客户端:

var socket = io('http://localhost:3000/public');
var user = Cookies.get('user');

socket.on('connect', function(){
 socket.emit('adduser', user); 
});

socket.on('server',function(msg){
    $('#conversation').append('<li> <b>Server: </b>'+msg+'</li>');
});

我正在dashboard/home上的home组件中加载此客户端脚本,当用户移动到dashboard/contacts时,它不会断开连接。它还会创建重复的套接字侦听器,因为每次加载组件时都会重新加载此客户端脚本。

移动到联系人路由:

正在重新加载Home组件

waxmsbnn

waxmsbnn1#

您可以生成一个Angular服务用于连接和断开连接。在所需组件的ngOnInit上调用该服务以连接,然后在ngOnDestroy方法上调用断开连接方法。
您也可以尝试像您所说的那样执行相同的Guards。

ngynwnxp

ngynwnxp2#

组件内部.ts

ngOnInit() {
   this.chatService.connect()
 }

 ngOnDestroy(){
   this.chatService.disconnectSocket();
 }

内部聊天服务

import { io, Socket } from "socket.io-client";

        private socket: Socket;

          constructor() {
            this.socket = io("http://localhost:4000");
          }

          connect(){
            this.socket.connect()
           }

           disconnectSocket(){
             this.socket.disconnect()
           }

相关问题