简体   繁体   English

Socket.IO双火

[英]Socket.IO double fire

I am using Socket.IO to send data from my client to my node.js server. 我正在使用Socket.IO将数据从客户端发送到我的node.js服务器。 When I receive the data from the client I am simply logging it. 当我从客户端收到数据时,我只是在记录它。 However the data logs two times where I only expect it to log once? 但是,数据记录两次,我只希望它记录一次?

Here is the client side code 这是客户端代码

btn.addEventListener("click", (e) => {
    socket.emit("comparison", "hello");
 });

Here is the server-side code 这是服务器端代码

app.get("/", (req, res) => {
  io.on("connection", (socket) => {
   socket.on("comparison", (data) => {
    console.log(data);  
    })
 })

It logs 'hello hello' 它记录“你好你好”

Any idea as to what this is? 关于这是什么想法吗?

UPDATE UPDATE

I still haven't fixed the problem although I've noticed when I take the socket code outside of the express route code there is only one log 我仍然没有解决问题,尽管我注意到当我将套接字代码带到快速路由代码之外时,只有一个日志

You shouldn't put io.on('connection') inside app.get('/'). 您不应将io.on('connection')放在app.get('/')内。 What you are doing here is registering an event listener on every get request. 您在这里所做的是在每个get请求上注册一个事件侦听器。 The reason why you are seeing two statements is directly related to the number of requests handled inside your app.get(). 您看到两个语句的原因与app.get()内部处理的请求数直接相关。

Take a look at the example provided in the socket.io site https://socket.io/docs/#Using-with-Express 看一下socket.io网站https://socket.io/docs/#Using-with-Express中提供的示例

I have added a simillar boilerplate of the code here, 我在这里添加了一个类似代码的样板,

const express        = require('express');
const bodyParser     = require('body-parser');
const app            = express();
const port           = 8000;

var server = require('http').createServer(app);
var io = require('socket.io')(server);

app.use(express.static(__dirname + '/app'));
app.use(bodyParser.urlencoded({ extended: true }));

server.listen(port,() => {
    console.log("server listening on"+port);
});

app.get('/', function(req, res){
  //do something
});


io.on('connection',function(socket){

  socket.on('comparison', function () {

  });

});

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

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