Skip to content

Instantly share code, notes, and snippets.

@ekryski
Last active February 19, 2019 20:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ekryski/59eb6ce5b2774fa24d15 to your computer and use it in GitHub Desktop.
Save ekryski/59eb6ce5b2774fa24d15 to your computer and use it in GitHub Desktop.
How to use socket.io in React Native
// You need to set `window.navigator` to something in order to use the socket.io
// client. You have to do it like this in order to use the debugger because the
// debugger in React Native runs in a webworker and only has a getter method for
// `window.navigator`.
window.navigator.userAgent = 'ReactNative';
// Need to require instead of import so we can set the user agent first
// This must be below your `window.navigator` hack above
const io = require('socket.io-client/socket.io');
const socket = io('http://chat.feathersjs.com', {
transports: ['websocket'] // you need to explicitly tell it to use websockets
});
socket.on('connect', () => {
console.log('connected!');
});
@gayashanbc
Copy link

gayashanbc commented May 28, 2018

This solution is not working for me :(
Can you please help me?
I'm running the app on Genymotion emulator. could that be a problem?

@mcmatan
Copy link

mcmatan commented Jun 12, 2018

Same here, not working for me on iOS

@r01010010
Copy link

r01010010 commented Jun 28, 2018

I only tried in Android, and this code is working for me so far:

  • react-native v0.44.0
  • socket.io-client v2.1.1
window.navigator.userAgent = "react-native"; // for some versions of socketio this is needed also in React Native
import io from 'socket.io-client/dist/socket.io'; // note the /dist/ subdirectory (socket.io-client v.2.1.1)!

const connectionConfig = {
  jsonp: false,
  reconnection: true,
  reconnectionDelay: 100,
  reconnectionAttempts: 100000,
  transports: ['websocket'], // you need to explicitly tell it to use websockets
};

socket = io(socketPath, connectionConfig);

socket.on('connect', function(){
  console.log('Socket connected!');
});

@ananth10
Copy link

ananth10 commented Jul 2, 2018

i am seeing warning socket.on is unresolved function or method. why? can anyone help me? and also i am getting this warning

Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment