React native socket io no events being emitted fro

2019-07-28 03:10发布

问题:

Trying to use socket.io-client with react-native (ios for now), so far connection / receiving server side events from client seems to be working fine. However I can't seem to emit any events from the client?

Client

var socket = io("http://localhost:3000");
    socket.on('connect', function(){
        socket.on('ping', function(e) {
            console.log('Server emitted ping: ' + e);
            socket.emit('pong', 'hi server!');
        });
        socket.on('disconnect', function(){
            console.log("disconnect");
        });
    });

Server(Node.js)

var io = require('socket.io')(server);
io.on('connection', function (socket) {
  console.log('connected...');
  socket.on('pong', function (data) {
    console.log("Hmm?");
    console.log(data);
  });

  setTimeout(function() {
    console.log("Saying hello");
    socket.emit('ping', { message: 'Hello from server ' + Date.now() });

  }, 1000);
});

So from the server side, I see the logs

connected...
Saying hello

And in the client I see "Server emitted ping...", but the pong event doesn't seem to be doing anything? I tried catching all events on the server through solutions mentioned in StackOverflow, but it looked like no event was coming from the client. Any ideas?

Using latest RN version 0.31.

Also seeing this error when I first run the app in Xcode, could it be the reason?:

[warn][tid:main][RCTEventEmitter.m:52] Sending `websocketFailed` with no listeners registered.

回答1:

please try:

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