刷新页面时套接字 IO 进行多个连接 - Node JS [英] Socket IO makes multiple connections when the page is refreshed - Node JS

查看:19
本文介绍了刷新页面时套接字 IO 进行多个连接 - Node JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个抓取工具,可以从所有网站抓取作业并将它们保存到数据库中.我已经制作了自己的默认日志,用于获取消息(错误、信息)等.我正在使用 socket.io 实时更新我的​​视图和数据库.

问题是当我启动应用程序时,它完美地获得了套接字和数据库连接.但是当我尝试刷新页面时,使用相同的消息和不同的 ID 再次建立了相同的连接两次.我刷新页面,连接已建立,id 已更改,但对于所有已建立的连接,它们使用一个 ID,

下面是显示它的日志:

我已上传视频,请查看此视频以及.尝试观看一开始,然后在 01:4103:06,在开始抓取第一个网站之前建立连接,但是当第二个网站抓取时开始时,Internet Connection 消息给出两次,同样表示启动第三次爬网时,消息数每次翻倍.我不知道为什么.

我尝试按照这个问题的答案进行操作,但仍然没有成功.代码在 server 文件上有 600 多行,第二个文件有 150 多行,在客户端也是如此,这就是为什么我不能全部上传,而且有点保密.

但是客户端和服务器端的socket连接是这样的:

服务器端

const express = require("express");const app = express();const scrap = require("./algorithm");const event = scrap.defEvent;//从另一个文件导入const ms_connect = scrap.ms_connect;const server = app.listen(8000, function(){ console.log('Listening on 8000'); });const io = require("socket.io").listen(server);const internetAvailable = require("internet-available");app.use(express.static(__dirname + "/"));app.get("/scrap",function(req,res){res.sendFile(__dirname+"/index.html");//设置默认路由io.on("connection",function(socket){//在套接字连接上socketSameMess("Socket",'在 ID 上建立的套接字连接:<span style="color:#03a9f4;">'+socket.id+'<span>');ms_connect.connect(function(err){//连接数据库if(err) socketSameMess("database_error",err+" ");//如果数据库连接有错误socketSameMess("数据库",'连接MYSQL数据库成功...');})})})函数 eventSameMess(auth,mess){//点击自定义控制台defEvent.emit("hitConsole",{a:auth,m:mess});}

客户端

var socket = io.connect('http://localhost:8000');socket.on('connect',function(){如果(套接字.连接){initDocument();}}) 

解决方案

获取多条消息

这是socketio的一些经验法则

  1. 如果您监听任何事件一次,您将在回调中收到一次消息

  2. 如果你监听任何事件两次,你会在回调中收到两次消息

  3. 如果您在 nth 次侦听任何事件,您将在回调中收到消息 nth

  4. 如果您在页面加载时监听任何事件,请不要忘记在离开页面之前监听该事件(如果事件不是全局的)

    • 如果您忘记收听,如果您再次访问页面.您将开始多次收听事件.因为在页面加载时您正在收听事件.并且之前的事件还没有被 listen off
    • 停止
  5. 不要在 loop 中侦听任何事件,它可能会侦听多次,并且您会在一次更改中收到多条消息.

连接套接字

const socket = io('http://localhost', {传输:['websocket'],升级:假});

监听和监听事件

let onMessage = (data) =>{控制台日志(数据);}//监听消息socket.on('message', onMessage);//停止监听消息socket.off('message', onMessage);

断开连接时删除所有侦听器

socket.on('disconnect', () => {socket.removeAllListeners();});


<块引用>

使用 Firecamp 直观地测试/调试 SocketIO 事件.

I have developed a scrapping tool, that scraps jobs from all websites and save them into the database. I have made my own default log where I get messages(errors, info) etc. I am using socket.io to update my view in real time and for database too.

The problem is when I start the app it perfectly get make socket, and database connections. But when I try to refresh the page, the same connection is made again twice with the same message and different ID's. As much I refresh the page the connections are made, and the id get changed, but for all made connection they use one ID,

Below is the Log which shows it :

I have uploaded this video, please check this as well. Try to watch the very beginning, and then at 01:41 and 03:06, before starting scrapping of the first site the connection is established, but when second website scrapping is started, the Internet Connection message is given twice, and the same stands for when third website scrapping is started, the number of messages get doubled every time. I don't know why.

I have tried following the answer of this question, but still no success. The code is 600+ lines on server file, and 150+ lines second file and same on the client side, that's why I can't upload all and it's a bit confidential.

But the socket connection on the client and server is like this:

Server Side

const express              =    require("express");
const app                  =    express();
const scrap                =    require("./algorithm");
const event = scrap.defEvent;//imported from another file 
const ms_connect = scrap.ms_connect;
const server = app.listen(8000, function(){ console.log('Listening on 8000'); });
const io                   =    require("socket.io").listen(server);
const internetAvailable    =    require("internet-available");
app.use(express.static(__dirname + "/"));


app.get("/scrap",function(req,res){
    res.sendFile(__dirname+"/index.html");//Set the Default Route
    io.on("connection",function(socket){ //On Socket Connection
        socketSameMess("Socket",'Sockets Connection Made on ID : <span style="color:#03a9f4;">'+socket.id+'<span>');
        ms_connect.connect(function(err){//On Connection with Database
            if(err) socketSameMess("database_error",err+" "); // If any error in database connection
            socketSameMess("Database ",'Connected to MYSQL Database Successfully...');
        })
    })
})

function eventSameMess(auth,mess){
    //hits the custom console
    defEvent.emit("hitConsole",{a:auth,m:mess});
}

Client Side

var socket = io.connect('http://localhost:8000');
socket.on('connect',function(){
    if(socket.connected){
        initDocument();
    }
})  

解决方案

Getting multiple messages

Here are some thumb rules for socketio

  1. if you listen to any event once, you'll get the message once in the callback

  2. if you listen to any event twice, you'll get the message twice in the callback

  3. if you listen to any event nth time, you'll get the message nth in the callback

  4. If you're listening to any event on page load, don't forget to listen off that event before you leave the page (if an event is not globally)

    • If you forgot to listen off and if you again re-visit page. you'll start listening to events multiple times. because on page load you're listening to the event. and the previous event is not yet stopped by listen off
  5. Don't listen to any event in loop, It may listen to it multiple time and you'll get multiple messages on a single change.

connect socket

const socket = io('http://localhost', {
  transports: ['websocket'], 
  upgrade: false
});

listen and listen off an event

let onMessage = (data) => {
  console.log(data);
}
//listen message
socket.on('message', onMessage);

//stop listening message
socket.off('message', onMessage);    

remove all listeners on disconnect

socket.on('disconnect', () => {
   socket.removeAllListeners();
});


Use Firecamp to test/debug SocketIO events visually.

这篇关于刷新页面时套接字 IO 进行多个连接 - Node JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆