Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io client is not working with React Native

I am using socket.io in the backend, it's working fine on the frontend with vanilla javascript using socket.io-client but when I try to connect socket.io through React Native I am getting the error:

Vanilla JS(Working Perfectly fine) :

   <script>

    var socket =  io.connect('http://localhost:9092');
    socket.on('connect', function() {
      output('<span class="connect-msg">Client has connected to the server!</span>');
   });

React Native code: (Not working)

 this.socket = io.connect('http://localhost:9092',{ 
 reconnection: true,
 reconnectionDelay: 500,
 jsonp: false,
 reconnectionAttempts: Infinity,
 transports: ['websocket']});

this.socket.on('connect',function(e){
  console.log("on Connect");
})

this.socket.on('connect_error', (err) => {
  console.log(err)
});

Error:

websocket error

Stack trace: node_modules/engine.io-client/lib/transport.js:67:22 in onError
node_modules/engine.io-client/lib/transports/websocket.js:157:17 in onerror node_modules/event-target-shim/lib/event-target.js:172:43 in dispatchEvent
node_modules/react-native/Libraries/WebSocket/WebSocket.js:290:10 in
node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:191:12 in emit
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:349:47 in __callFunction
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:106:26 in
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:297:10 in __guard
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:105:17 in callFunctionReturnFlushedQueue

I am using https://github.com/mrniko/netty-socketio in the backend.

React Native app has been created using expo-cli.

like image 819
Dhaval Soni Avatar asked Feb 12 '26 15:02

Dhaval Soni


1 Answers

Instead of using localhost try getting an IP remember the IP on both sides phone and PC should be same but with different ports and this will solve your error probably

this.socket = io.connect('http://localhost:9092'}

to

this.socket = io.connect('http://192.x.x.x.x:9092'}

like image 150
somesh balani Avatar answered Feb 15 '26 00:02

somesh balani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!