Socket.io-client: Impossible de se connecter via socket.io-client sur react-native

Créé le 31 oct. 2018  ·  37Commentaires  ·  Source: socketio/socket.io-client

You want to: Vous voulez:

  • [x] report a bug [x] signaler un bogue
  • [ ] request a feature [ ] demander une fonctionnalité

Current behaviour Comportement actuel

I can't connect via socket io to my server, it times out. Je ne peux pas me connecter via socket io à mon serveur, il expire.

Steps to reproduce (if the current behaviour is a bug) Étapes à reproduire (si le comportement actuel est un bogue)

In react-native: En natif réactif :

import io from 'socket.io-client';


const BACKEND = 'my socketio server url'

const sock = io(BACKEND, { transports: ['websocket'], forceNew: true });
sock.on('connected', () => {
  debugger;
})

The debug logs look like: Les journaux de débogage ressemblent à :

socket.io-client:url parse <my url> +0ms
browser.js:133 socket.io-client ignoring socket cache for <my url> +0ms
browser.js:133 socket.io-client:manager readyState closed +0ms
browser.js:133 socket.io-client:manager opening <my url> +1ms
browser.js:133 engine.io-client:socket creating transport "websocket" +0ms
browser.js:133 engine.io-client:socket setting transport websocket +3ms
browser.js:133 socket.io-client:manager connect attempt will timeout after 20000 +6ms
browser.js:133 socket.io-client:manager readyState opening +2ms
socket.io-client:manager connect attempt timed out after 20000 +20s
browser.js:133 engine.io-client:socket socket close with reason: "forced close" +20s
browser.js:133 engine.io-client:socket socket closing - telling transport to close +2ms
browser.js:133 socket.io-client:manager connect_error +3ms
browser.js:133 socket.io-client:manager cleanup +1ms
browser.js:133 socket.io-client:manager will wait 899ms before reconnect attempt +1ms
browser.js:133 socket.io-client:manager attempting reconnect +912ms

Note : the best way (and by that we mean the only way ) to get a quick answer is to provide a failing test case by forking the following fiddle . Remarque : le meilleur moyen (et nous entendons par là le seul moyen ) d'obtenir une réponse rapide est de fournir un cas de test défaillant en bifurquant le violon suivant.

Expected behaviour Comportement attendu

I expect to be able to connect to my socketio server, the same way I am able to in a web browser. Je m'attends à pouvoir me connecter à mon serveur socketio, de la même manière que dans un navigateur Web.

Setup Installer

  • OS: iOS iPhone 10 simulator Système d'exploitation : simulateur iOS iPhone 10
  • browser: React-native navigateur : React-native
  • socket.io version: 2.1.1 version socket.io : 2.1.1
en

Commentaire le plus utile

Finally found a solution for React Native >= 0.60 after a couple of coffees and digging deep into engine.io - additional to a version conflict (with RN) there seems to be an issue with passing in the URI. Enfin trouvé une solution pour React Native >= 0.60 après quelques cafés et en creusant profondément dans engine.io - en plus d'un conflit de version (avec RN), il semble y avoir un problème avec le passage de l'URI. When I pass an URI into socketIO, it gets turncated to the host and 'socket.io' appened. Lorsque je passe un URI dans socketIO, il est renvoyé à l'hôte et 'socket.io' est ajouté. So socketIO("https://foo.bar/my/endpoint/socket.io") will lead to socketIO trying to connect to https://foo.bar/socket.io without showing it in the logs when throwing the xhr pull / socket error. Ainsi, socketIO("https://foo.bar/my/endpoint/socket.io") conduira socketIO à essayer de se connecter à https://foo.bar/socket.io sans l'afficher dans les journaux lors de la génération de l'erreur xhr pull/socket.

Here we go, how to get socket.io running on current versions of React Native : C'est parti, comment faire fonctionner socket.io sur les versions actuelles de React Native :

  • use socket.io-client version _2.1.1_ utiliser socket.io-client version _2.1.1_
// package.json
{
  "dependencies": {
     "socket.io-client": "2.1.1"
   }
}
  • when setting up the client, define a host and a path lors de la configuration du client, définissez un hôte et un chemin
const socket = socketIO('https://your.host.com/', {
  path: '/path/to/socket.io/'
})
  • and suddenly everything works as smooth as planed et tout à coup tout fonctionne aussi bien que prévu

Hope to have saved you the time I spent on this issue 😆 J'espère vous avoir fait gagner du temps sur ce problème 😆

en

Tous les 37 commentaires

Looks like this is react-native's issue. On dirait que c'est le problème de react-native. Earlier versions of RN seem to work with socket.io, but 0.0.57 does not. Les versions antérieures de RN semblent fonctionner avec socket.io, mais pas la 0.0.57. Closing. Fermeture.

en

Try "socket.io-client": "2.0.4" Essayez "socket.io-client": "2.0.4"
This may be socket.io bug Cela peut être un bogue socket.io

en

Try "socket.io-client": "2.0.4" Essayez "socket.io-client": "2.0.4"
This may be socket.io bug Cela peut être un bogue socket.io

Yes it does work. Oui ça marche.

en

Avec RN 0.52 et socket.io-client 2.0.4, je suis toujours confronté à ce problème.

en

@noahprince22 can you please share your configuration ? @noahprince22 pouvez-vous s'il vous plaît partager votre configuration ?
I am currently using this and the issue still persist. Je l'utilise actuellement et le problème persiste toujours.

"react-native": "0.55.4",
"react": "16.3.1",
"socket.io-client": "^2.0.4",
"socket.io: "^2.2.0" //server side
en

any workaround? une solution de contournement ?

socket.io team please, this should work with RN, is a socket.io bug. équipe socket.io s'il vous plaît, cela devrait fonctionner avec RN, est un bogue socket.io.

en

Hi @ningacoding , I managed to get it working with this configuration Salut @ningacoding , j'ai réussi à le faire fonctionner avec cette configuration

"react-native": "0.55.4",
"react": "16.3.1",
"socket.io-client": "^2.0.4",
"socket.io: "^1.0.0" //server side

In your react-native app use this Dans votre application réactive native, utilisez ceci

const socket = io(BASE_URL, {
    secure: true,
    transports: ['websocket'],
  });
en

"react-native": "0.58.6", "réagir natif": "0.58.6",
"react": "16.6.3", "réagir": "16.6.3",
"socket.io-client": "^2.0.4", "socket.io-client": "^2.0.4",

Not working for me Ne fonctionne pas pour moi

en

any solution? Toute solution? I'm facing the same thing je suis confronté à la même chose

en

I have long since stopped working on the project that I was having this issue with. J'ai depuis longtemps cessé de travailler sur le projet avec lequel j'avais ce problème. If I remember correctly, I downgraded react-native to "solve' the problem. Si je me souviens bien, j'ai rétrogradé react-native pour "résoudre" le problème.

en

Experiencing the same issue, has there been a fix yet? Vous rencontrez le même problème, y a-t-il déjà eu un correctif ? Anyone find any workarounds to implementing sockets in React Native? Quelqu'un a-t-il trouvé des solutions de contournement pour implémenter des sockets dans React Native ?

en

@russellgoldman I had problems with RN 0.60.5 and socket.io. @russellgoldman J'ai eu des problèmes avec RN 0.60.5 et socket.io. Release build did not connect to the server. La version de version ne s'est pas connectée au serveur.

None of socket.io versions worked with RN 0.60.5: I tried versions 2.0.4, 2.1.1, 2.2.0. Aucune des versions de socket.io ne fonctionnait avec RN 0.60.5 : j'ai essayé les versions 2.0.4, 2.1.1, 2.2.0.

Downgrading to RN 0.59.10 solved my problem. La rétrogradation vers RN 0.59.10 a résolu mon problème.

en

Hi @anttirauh and @russellgoldman , Salut @anttirauh et @russellgoldman ,
I tried with RN 0.59.10 and Socket 2.0.4, but its not connecting on release build. J'ai essayé avec RN 0.59.10 et Socket 2.0.4, mais il ne se connecte pas à la version publiée.
Can you please help me? Pouvez-vous m'aider s'il vous plaît?

en

@ Ramesh21071993 Je pense que vous devez mettre à jour socket.io vers la version 2.1.1.

en

@anttirauh , i tried with all these versions socket io (2.0.4, 2.1.1, 2.2.0) and react-native versions (0.60, 0.59.10, 0.59.4) @anttirauh , j'ai essayé avec toutes ces versions socket io (2.0.4, 2.1.1, 2.2.0) et les versions réactives (0.60, 0.59.10, 0.59.4)
In server side also socket io 2.0.4. Du côté serveur également socket io 2.0.4.
still that same issue sir, toujours le même problème monsieur,

But it works on RN 0.55.4 Mais cela fonctionne sur RN 0.55.4

en

@Ramesh21071993 My understanding (which is formed with heavy googling and own testing) is that: @ Ramesh21071993 Ma compréhension (qui est formée avec de nombreux tests sur Google et mes propres tests) est que :

  • socket.io stopped working with react-native about around RN version 0.57.4 socket.io a cessé de fonctionner avec react-native à propos de la version RN 0.57.4
  • socket.io or some other component was fixed later and I managed to get it working with version combo: RN 0.59.10 + socket.io 2.1.1 socket.io ou un autre composant a été corrigé plus tard et j'ai réussi à le faire fonctionner avec la version combo : RN 0.59.10 + socket.io 2.1.1
  • RN version 0.60.x is not working with any version of socket.io La version RN 0.60.x ne fonctionne avec aucune version de socket.io

So my advice is only: try one time more with RN 0.59.10 and socket.io 2.1.1 and make sure that you clear build folder before building. Donc, mon conseil est seulement : essayez une fois de plus avec RN 0.59.10 et socket.io 2.1.1 et assurez-vous d'effacer le dossier de construction avant de construire. And remove node_modules before yarn/npm. Et supprimez node_modules avant yarn/npm.

en

@anttirauh Sir, below is my package.json. @anttirauh Monsieur, voici mon package.json. I did as what you told. J'ai fait comme tu m'as dit. But nothing happen. Mais rien ne se passe. I remove build folder and node modules and again i install. Je supprime le dossier de construction et les modules de nœud, puis j'installe à nouveau.
Please help me on this to work, Past one month am trying S'il vous plaît aidez-moi sur ce travail, passé un mois j'essaie

App package.json Package d'application.json

{ {
"name": "Track", "nom": "Piste",
"version": "0.0.1", "version": "0.0.1",
"private": true, "privé": vrai,
"scripts": { "scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start", "start": "nœud node_modules/react-native/local-cli/cli.js start",
"test": "jest" "test": "plaisanterie"
}, },
"dependencies": { "dépendances": {
"react": "16.8.3", "réagir": "16.8.3",
"react-native": "0.59.10", "react-native": "0.59.10",
"socket.io": "2.1.1" "socket.io": "2.1.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.6.2", "@babel/core": "^7.6.2",
"@babel/runtime": "^7.6.2", "@babel/runtime": "^7.6.2",
"babel-jest": "^24.9.0", "babel-jest": "^24.9.0",
"jest": "^24.9.0", "plaisanterie": "^24.9.0",
"metro-react-native-babel-preset": "^0.56.0", "metro-react-native-babel-preset": "^0.56.0",
"react-test-renderer": "16.8.3" "react-test-renderer": "16.8.3"
}, },
"jest": { "plaisanterie": {
"preset": "react-native" "preset": "réagir natif"
} }
} }

Server Package.json Serveur Package.json

{ {
"name": "TRACK-Socket", "name": "TRACK-Socket",
"version": "0.0.1", "version": "0.0.1",
"dependencies": { "dépendances": {
"amqplib": "^0.5.1", "amqplib": "^0.5.1",
"config": "^3.2.2", "config": "^3.2.2",
"express": "^4.15.3", "express": "^4.15.3",
"socket.io": "^2.1.1", "socket.io": "^2.1.1",
"ws": "^7.1.2" "ws": "^7.1.2"
} }
} }

Thanks Merci

en

Finally found a solution for React Native >= 0.60 after a couple of coffees and digging deep into engine.io - additional to a version conflict (with RN) there seems to be an issue with passing in the URI. Enfin trouvé une solution pour React Native >= 0.60 après quelques cafés et en creusant profondément dans engine.io - en plus d'un conflit de version (avec RN), il semble y avoir un problème avec le passage de l'URI. When I pass an URI into socketIO, it gets turncated to the host and 'socket.io' appened. Lorsque je passe un URI dans socketIO, il est renvoyé à l'hôte et 'socket.io' est ajouté. So socketIO("https://foo.bar/my/endpoint/socket.io") will lead to socketIO trying to connect to https://foo.bar/socket.io without showing it in the logs when throwing the xhr pull / socket error. Ainsi, socketIO("https://foo.bar/my/endpoint/socket.io") conduira socketIO à essayer de se connecter à https://foo.bar/socket.io sans l'afficher dans les journaux lors de la génération de l'erreur xhr pull/socket.

Here we go, how to get socket.io running on current versions of React Native : C'est parti, comment faire fonctionner socket.io sur les versions actuelles de React Native :

  • use socket.io-client version _2.1.1_ utiliser socket.io-client version _2.1.1_
// package.json
{
  "dependencies": {
     "socket.io-client": "2.1.1"
   }
}
  • when setting up the client, define a host and a path lors de la configuration du client, définissez un hôte et un chemin
const socket = socketIO('https://your.host.com/', {
  path: '/path/to/socket.io/'
})
  • and suddenly everything works as smooth as planed et tout à coup tout fonctionne aussi bien que prévu

Hope to have saved you the time I spent on this issue 😆 J'espère vous avoir fait gagner du temps sur ce problème 😆

en

@rastapasta , i got an error like “ CLEARTEXT communication not permitted by network security policy ”, @rastapasta , j'ai eu une erreur du type " Communication CLEARTEXT non autorisée par la politique de sécurité du réseau ",

Please tell me what to do S'il vous plaît dites-moi ce qu'il faut faire

en

@Ramesh21071993 if you can't use your endpoint via https (please consider it), add their hostnames to the exception lists. @ Ramesh21071993 si vous ne pouvez pas utiliser votre point de terminaison via https (veuillez en tenir compte), ajoutez leurs noms d'hôte aux listes d'exceptions.

for iOS: https://stackoverflow.com/a/30732693 pour iOS : https://stackoverflow.com/a/30732693
for Android: https://stackoverflow.com/a/50834600 pour Android : https://stackoverflow.com/a/50834600

en

Sir, I tried that also but not able to do. Monsieur, j'ai essayé cela aussi mais je n'ai pas pu le faire. If you don't mind can you please give me any demo source files Si cela ne vous dérange pas, pouvez-vous s'il vous plaît me donner des fichiers source de démonstration
For long time I struck with this. Pendant longtemps j'ai frappé avec ça.

Am using ip and port sir J'utilise ip et port monsieur

en

suivez les instructions des documentations ci -dessus et adaptez cette implémentation :

import socketIO from 'socket.io-client'
const socket = socketIO('http://8.8.8.8:3000/', {
  path: '/your/path/to/socket.io/'
  reconnectionDelay: 1000,
  reconnection: true,
  reconnectionAttempts: Infinity,
  jsonp: false
})

socket.on('connect', () => console.log('connected'))
socket.on('error', console.error)
socket.on('connect_error', console.error)
en

Monsieur, côté serveur, j'utilise socket io 2.1.1, est-ce que ça va ou quelque chose doit changer

en

image

en

@Lizhooh façon hacky de découvrir whazzup sur rn: patch de singe un console.log(err) avant le self.onError dans votre node_modules engine.io-client/blob/master/lib/transports/ polling-xhr.js #L131

en

@Ramesh21071993 Is your issue resolved? @ Ramesh21071993 Votre problème est-il résolu ? I am facing the same issue. Je suis confronté au même problème. Tried everything mentioned in above comments. J'ai essayé tout ce qui est mentionné dans les commentaires ci-dessus.

en

@rastapasta I followed what you have suggested above. @rastapasta J'ai suivi ce que vous avez suggéré ci-dessus. My socket connection happens and then immediately disconnects. Ma connexion socket se produit puis se déconnecte immédiatement. I get timeout error infinitely. J'obtiens une erreur de délai d'attente à l'infini. However, whenever I click on some component which makes a network call, the socket connects and immediately disconnects. Cependant, chaque fois que je clique sur un composant qui effectue un appel réseau, le socket se connecte et se déconnecte immédiatement. If I don't do any network call after first socket disconnect, it would stay in the same state. Si je ne fais aucun appel réseau après la première déconnexion du socket, il resterait dans le même état. Please, could you help? S'il vous plaît, pourriez-vous aider?

socket = io('http://IP:31515', { socket = io('http://IP:31515', {
path: '/socketio', //I have given this is the path in my socket server as well as my kubernetes ingress file to route to that port path: '/socketio', // j'ai donné ceci est le chemin dans mon serveur de socket ainsi que mon fichier d'entrée kubernetes pour acheminer vers ce port
transports: ['websocket'], transports : ['websocket'],
reconnectionDelay: 1000, délai de reconnexion : 1000,
reconnection: true, reconnexion : vrai,
reconnectionAttempts: Infinity, tentatives de reconnexion : Infini,
// timeout: 30000, // délai : 30000,
jsonp: false jsonp : faux
}); });

things that I have tried: choses que j'ai essayé:

  1. removing and adding transports option option de suppression et d'ajout de transports
    2.removing and add timeout 2. supprimer et ajouter un délai d'attente
  2. removing all parameters except path supprimer tous les paramètres sauf le chemin
  3. adding pingTimeout and pingInterval in server socket configuration ajout de pingTimeout et pingInterval dans la configuration du socket du serveur
  4. removing path from server and client and only keeping it in my kubernetes ingress file to route to that deployment/pod. supprimer le chemin du serveur et du client et ne le conserver que dans mon fichier d'entrée kubernetes pour acheminer vers ce déploiement/pod.

Note: the same server and kubernetes conf work for any node.js socket client as well as my react js web app. Remarque : le même serveur et la même configuration kubernetes fonctionnent pour n'importe quel client de socket node.js ainsi que pour mon application Web React js. I am only facing this issue for React Native app in debug as well as release mode. Je ne rencontre ce problème que pour l'application React Native en mode débogage et en mode de publication.

en

Quelqu'un a-t-il une idée pour mon problème ci-dessus?

en

@calqlum123 @calqlum123
Please make sure to Veuillez vous assurer de

  • add your host to the transport exception list (s. here ) ajoutez votre hôte à la liste des exceptions de transport (voir ici )
  • try it without manually defining the transports essayez sans définir manuellement les transports
  • monkey patch the console.log (s. here ) and check the error patcher le fichier console.log (voir ici ) et vérifier l'erreur
en

Can anyone please share a complete working example for both client and server? Quelqu'un peut-il partager un exemple de travail complet pour le client et le serveur ? Because this is confusing. Parce que c'est déroutant.

en

I am using "react-native": "0.61.5" and "socket.io-client": "^2.1.1", J'utilise "react-native": "0.61.5" et "socket.io-client": "^2.1.1",

below is my code ci-dessous mon code

const socket = SocketIOClient('http://192.168.0.101:1234',{reconnect: true}); socket.connect(); socket.once("connect", () => { console.log("[CLIENT] Connected to remote server, identificating."); // this.sendIdentification(); }); socket.on('connect', () => { console.log('connected to socket server'); });

The code is not able to connect to the server and I am also looking for the solution. Le code n'arrive pas à se connecter au serveur et je cherche également la solution. I don't want to downgrade my react-native version. Je ne veux pas rétrograder ma version réactive native.

en

you must add this code in application tag vous devez ajouter ce code dans la balise d'application
like below in AndroidManifest.xml comme ci-dessous dans AndroidManifest.xml
. . . . . .

en

I am using "react-native": "0.61.5" and "socket.io-client": "^2.1.1", J'utilise "react-native": "0.61.5" et "socket.io-client": "^2.1.1",

below is my code ci-dessous mon code

const socket = SocketIOClient('http://192.168.0.101:1234',{reconnect: true}); socket.connect(); socket.once("connect", () => { console.log("[CLIENT] Connected to remote server, identificating."); // this.sendIdentification(); }); socket.on('connect', () => { console.log('connected to socket server'); });

The code is not able to connect to the server and I am also looking for the solution. Le code n'arrive pas à se connecter au serveur et je cherche également la solution. I don't want to downgrade my react-native version. Je ne veux pas rétrograder ma version réactive native.

Can you try "ws://192.168.0.101:1234", instead of " http://192.168.0.101 :1234" Pouvez-vous essayer "ws://192.168.0.101:1234", au lieu de " http://192.168.0.101 :1234"

en

@Unforgiven-wanda un exemple avec React Native a été ajouté ici : https://github.com/socketio/socket.io/tree/master/examples/react-native

en

Impossible de se connecter avec "socket.io-client": "^ 3.0.4" en réaction native

en

@chiragpurohit71085 have you checked the example there: https://github.com/socketio/socket.io/tree/master/examples/react-native? @ chiragpurohit71085 avez-vous vérifié l'exemple ici : https://github.com/socketio/socket.io/tree/master/examples/react-native ?

I think that this is a problem of URL, could you please check if your server is reachable at http://192.168.x.y:z ? Je pense qu'il s'agit d'un problème d'URL, pourriez-vous vérifier si votre serveur est joignable à http://192.168.x.y:z ?

en
Cette page vous a été utile?
0 / 5 - 0 notes