Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

socket.emit not working inside socket.on server side #3565

Closed
1 of 2 tasks
BirdBare opened this issue Mar 20, 2020 · 3 comments
Closed
1 of 2 tasks

socket.emit not working inside socket.on server side #3565

BirdBare opened this issue Mar 20, 2020 · 3 comments

Comments

@BirdBare
Copy link

BirdBare commented Mar 20, 2020

You want to:

  • report a bug
  • request a feature

Current behaviour

*I cannot socket.emit from inside a socket.on callback on the server

Steps to reproduce (if the current behaviour is a bug)

Try to socket.emit inside of a socket.on from server side

Expected behaviour

The client to receive the message specific to their connection

Setup

  • OS: Ubuntu
  • browser: Chrome
  • socket.io version: 2.3.0 from npm install

Code

I cannot use io.emit or io.socket.emit because I only want the message to go to the requesting client. The issue has equals in front to help you find it.

var strains = "*DELETED";
var effects = "*DELETED";

strains = strains.replace(/\n/g," ");
strains = strains.replace(/ {2,}/g," ");
effects = effects.replace(/\n/g," ");
effects = effects.replace(/ {2,}/g," ");
//replace all newlines with spaces then remove all excess spaces. Should now
//match database.

const autocomplete = strains + effects;

var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var request = require("request");

http.listen(8080);

//create website
app.get ('/', function(request, response) 
{
  response.sendFile(__dirname + "/index.html");
});

//access local folder
app.use('/', express.static(__dirname));

//connect to socket from webpage
io.on("connection", function(socket)
{
  socket.emit("autocomplete",autocomplete);
  //emit on connection for autocomplete source

  socket.on("recommend", function(data)
  {
    if(data.length > 0)
    {
      data = data.split(",");
    
      lcStrains = strains.toLowerCase().split(",");
      lcEffects = effects.toLowerCase().split(",");

      var strainTags = [];
      var effectTags = [];
      var garbageTags = [];

      data.forEach(element =>
      {
        if(lcStrains.indexOf(element) != -1)
        {
      
          strainTags.push(element);
        }
        else if(lcEffects.indexOf(element) != -1)
        {
          effectTags.push(element);
        }
        else
        {
          garbageTags.push(element);
        }
        //get indexof element. If -1 then element is not present in the array
        //and will be put in garbage array
      });
    
      strainTags = strainTags.toString();
      effectTags = effectTags.toString();
      garbageTags = garbageTags.toString();

      console.log("...List of Tags...");
      console.log("Strains: " + strainTags);
      console.log("Effects: " + effectTags);
      console.log("Garbage: " + garbageTags);

      if(strainTags.length > 0 || effectTags.length > 0)
      {
        console.log("rec");
        const url = "*DELETED"
        const request_parameters = 
        {  
        "liked_strains": strainTags,
        "liked_effects": effectTags,
        "return_details": true,
        };

        request({url:url, qs:request_parameters}, function(err,reponse,body)
        {
          console.log(reponse.statusCode);
====socket.emit("result",JSON.stringify(JSON.parse(body).recommendations.results));
          //send result to client side in non JSON format.
        });
      }
    }

  });
 
  //api search if I can figure out source in autocomplete.
  socket.on("search", function(data)
  {
    console.log(data);

    const url = "*DELETED"
    const request_parameters = 
    { 
    "text": data,
    "category": "",
    "page" : "",
    "results_per_page" : "15",
    };

    request({url:url, qs:request_parameters}, function(err,reponse,body)
    {
      console.log(reponse.statusCode);
      console.log(body);
    });
  });
});
@BirdBare
Copy link
Author

Little info.

I tried to run socket.emit inside socket.on on the client side and it worked fine. Must be a server side bug.

I also tried io.to(socket.id).emit on server side to no avail.

@sghofrany
Copy link

sghofrany commented Mar 25, 2020

If you are trying to emit to a specific client you can use something like this.

io.on("connection", (socket) => {

//this will emit your event with the data specified only to the one client with that socket.id

io.to(socket.id).emit("your-event", yourData)

)};

EDIT: I just saw that you have tried this as well. I'm not sure as to what your problem might be, because I am also using socket.io version 2.3.0 and this seems to work just fine for me.

@BirdBare
Copy link
Author

I decided to use the callback functionality to reply directly to the requestor. It makes the design a little easier as well. I couldn't get it to work when having an emit event(or similar) directly inside a .on event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants