简体   繁体   English

刷新页面时套接字 IO 进行多个连接 - Node JS

[英]Socket IO makes multiple connections when the page is refreshed - Node JS

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.我已经制作了自己的默认日志,用于获取消息(错误、信息)等。我正在使用 socket.io 实时更新我的​​视图和数据库。

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.但是当我尝试刷新页面时,使用相同的消息和不同的 ID 再次建立了相同的连接两次。 As much I refresh the page the connections are made, and the id get changed, but for all made connection they use one ID,我刷新页面,连接已建立,id 已更改,但对于所有已建立的连接,它们使用一个 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.尝试看一开始,然后在01:4103:06 ,在开始第一个站点的03:06之前建立了连接,但是在开始第二个站点抓取时, Internet Connection消息给出了两次,并且相同因为当第三次网站抓取开始时,消息数量每次都会增加一倍。 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.代码在server文件上有 600 多行,第二个文件有 150 多行,在客户端也是如此,这就是为什么我不能全部上传,而且有点保密。

But the socket connection on the client and server is like this:但是客户端和服务器端的socket连接是这样的:

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这是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如果您第 n次收听任何事件,您将在回调中收到第 n 个消息

  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)如果您在页面加载时监听任何事件,请不要忘记在离开页面之前listen off该事件(如果事件不是全局的)

    • If you forgot to listen off and if you again re-visit page.如果您忘记listen off并再次访问页面。 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并且上一个事件还没有被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.不要在loop侦听任何事件,它可能会多次侦听它,并且您将在一次更改中收到多条消息。

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.使用Firecamp 直观地测试/调试 SocketIO 事件。

i was having the problem that each client was getting two socket connections.我遇到的问题是每个客户端都获得了两个套接字连接。 I thought something is wrong with sockets.我认为套接字有问题。 but the problem was但问题是

  • FrontEnd -> React前端 -> 反应
  • Created the template using create-react-app使用 create-react-app 创建模板
  • In index.js file it uses something called React.StrictMode在 index.js 文件中,它使用了一种叫做 React.StrictMode 的东西
  • This mode renders some of the App.js components two times.这种模式会两次渲染一些 App.js 组件。
  • Just remove that React.StrictMode and try to see if your problem is solved.只需删除该 React.StrictMode 并尝试查看您的问题是否已解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM