question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

socket.io emit not working

See original GitHub issue

I am using socket.io client and server(nodejs)

on connect I am using emit but it is not doing anything

my server code

const app = require("express")();
const server = require("http").createServer(app);
app.use(function (req, res, next) {

    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);

    next();
});

const io = require("socket.io")(server, {
    cors: {
      origin: '*',
    }
  });

io.on("connection", (socket) => {
    console.log("Connected!");
    socket.emit('on connect testing');
    io.emit('on connect testing2');
});

var redis = require('redis');  
//var url = "redis://:@localhost:6379"; 
//var redis = require('redis-url').connect();
//var client = redis.createClient(url);  
var client = redis.createClient();  
//var client = redis.createClient();
client.on("error", function(error) {
  console.error(error);
});
client.subscribe('notification');
client.on('message', function(channel, msg) {  
  console.log("Message received: "+msg);
  io.sockets.emit(msg);
  console.log('emitted');
});



console.log('starting server on 8001...');
server.listen(8001);

my index.html

<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh"
crossorigin="anonymous"></script>
<script>
    var socket;
    function createSocket(host) {
        return io(host, { transports : ['websocket'] }); 

        //if (window.WebSocket){
          //  console.log('1');
            //return new WebSocket(host);
        //} else if (window.MozWebSocket){
          //  console.log('2');
            //return new MozWebSocket(host);
        //}
    }
    function init() {
        var host = "ws://localhost:8001";
        try {
            socket = createSocket(host);
            console.log('3');
            socket.onconnect = function(msg) {
              console.log('In Connect with msg: '+msg);
            };
            socket.onopen = function(msg) {
              console.log('In Open with msg: '+msg);
            };
            send();
            socket.onmessage = function(msg) {
                  //var jsonmsg = JSON.parse(msg.data)
              console.log('In onmessage with msg: '+msg);
            };
            socket.onclose = function(msg) {
              console.log('In Close with msg: '+msg);
            };            
        }
        catch (ex) {
            console.log('4');
            console.log(ex);
        }
    }
    function quit() {
        console.log('5');
        socket.close();
    }
    function send() {
        console.log('7');
        socket.emit('some event');
    }
    setInterval(function(){
        if(!(socket.readyState == 1)){
          console.log('6');
          init();
        }
    }, 90000);
    init();
    
</script>

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
doug-shontzcommented, Mar 17, 2021

I’ll see what I can do to carve it out. It’s residing in a number of different modules in NDA covered code. I’ll need to break it out into a separate repo.

0reactions
darrachequesnecommented, Mar 18, 2021

@gsudhanshu you have a working example here: https://github.com/socketio/socket.io-fiddle

Please also check the examples directory: https://github.com/socketio/socket.io/tree/master/examples

Read more comments on GitHub >

github_iconTop Results From Across the Web

Node.js, Socket.io emit not working - Stack Overflow
I am making a website in Socket.io . But emit method not working in my code. I can't see any errors in my...
Read more >
Emitting events | Socket.IO
IO API is inspired from the Node.js EventEmitter, which means you can emit events on one side and register listeners on the other:....
Read more >
Troubleshooting connection issues | Socket.IO
First and foremost, please note that disconnections are common and expected, even on a stable Internet connection:
Read more >
Client API - Socket.IO
socket.emit(eventName[, ...args][, ack])​ ... Emits an event to the socket identified by the string name. Any other parameters can be included.
Read more >
The Socket instance (client-side)
connect; connect_error; disconnect. Please note that since Socket.IO v3, the Socket instance does not emit any event related to ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found