Socket.io-client: No se puede conectar a través de socket.io-client en react-native

Creado en 31 oct. 2018  ·  37Comentarios  ·  Fuente: socketio/socket.io-client

You want to: Tú quieres:

  • [x] report a bug [x] informar de un error
  • [ ] request a feature [ ] solicitar una característica

Current behaviour Comportamiento actual

I can't connect via socket io to my server, it times out. No puedo conectarme a través de socket io a mi servidor, se agota el tiempo de espera.

Steps to reproduce (if the current behaviour is a bug) Pasos para reproducir (si el comportamiento actual es un error)

In react-native: En reaccionar nativo:

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: Los registros de depuración se parecen a:

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 . Nota : la mejor manera (y con eso nos referimos a la única manera ) de obtener una respuesta rápida es proporcionar un caso de prueba fallido bifurcando el siguiente violín .

Expected behaviour Comportamiento esperado

I expect to be able to connect to my socketio server, the same way I am able to in a web browser. Espero poder conectarme a mi servidor socketio, de la misma manera que puedo hacerlo en un navegador web.

Setup Configuración

  • OS: iOS iPhone 10 simulator SO: Simulador iOS iPhone 10
  • browser: React-native navegador: React-nativo
  • socket.io version: 2.1.1 versión socket.io: 2.1.1
en

Comentario más útil

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. Finalmente , encontré una solución para React Native> = 0.60 después de un par de cafés y profundizando en engine.io; además de un conflicto de versión (con RN), parece haber un problema al pasar el URI. When I pass an URI into socketIO, it gets turncated to the host and 'socket.io' appened. Cuando paso un URI a socketIO, se conecta al host y se agrega 'socket.io'. 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. Por lo tanto socketIO("https://foo.bar/my/endpoint/socket.io") hará que socketIO intente conectarse a https://foo.bar/socket.io sin mostrarlo en los registros al arrojar el error xhr pull/socket.

Here we go, how to get socket.io running on current versions of React Native : Aquí vamos, cómo hacer que socket.io se ejecute en las versiones actuales de React Native :

  • use socket.io-client version _2.1.1_ usar socket.io-client versión _2.1.1_
// package.json
{
  "dependencies": {
     "socket.io-client": "2.1.1"
   }
}
  • when setting up the client, define a host and a path al configurar el cliente, defina un host y una ruta
const socket = socketIO('https://your.host.com/', {
  path: '/path/to/socket.io/'
})
  • and suddenly everything works as smooth as planed y de repente todo funciona tan bien como estaba planeado

Hope to have saved you the time I spent on this issue 😆 Espero haberles ahorrado el tiempo que dediqué a este tema 😆

en

Todos 37 comentarios

Looks like this is react-native's issue. Parece que este es un problema de react-native. Earlier versions of RN seem to work with socket.io, but 0.0.57 does not. Las versiones anteriores de RN parecen funcionar con socket.io, pero la 0.0.57 no. Closing. Clausura.

en

Try "socket.io-client": "2.0.4" Pruebe "socket.io-client": "2.0.4"
This may be socket.io bug Esto puede ser un error de socket.io

en

Try "socket.io-client": "2.0.4" Pruebe "socket.io-client": "2.0.4"
This may be socket.io bug Esto puede ser un error de socket.io

Yes it does work. Sí, funciona.

en

Con RN 0.52 y socket.io-client 2.0.4 sigo enfrentando este problema.

en

@noahprince22 can you please share your configuration ? @noahprince22 ¿puede compartir su configuración?
I am currently using this and the issue still persist. Actualmente estoy usando esto y el problema aún persiste.

"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? alguna solución?

socket.io team please, this should work with RN, is a socket.io bug. Equipo de socket.io, por favor, esto debería funcionar con RN, es un error de socket.io.

en

Hi @ningacoding , I managed to get it working with this configuration Hola @ningacoding , logré hacerlo funcionar con esta configuración

"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 En su aplicación nativa de reacción, use esto

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

"react-native": "0.58.6", "reaccionar nativo": "0.58.6",
"react": "16.6.3", "reaccionar": "16.6.3",
"socket.io-client": "^2.0.4", "socket.io-cliente": "^2.0.4",

Not working for me no funciona para mi

en

any solution? ¿alguna solución? I'm facing the same thing estoy enfrentando lo mismo

en

I have long since stopped working on the project that I was having this issue with. Hace tiempo que dejé de trabajar en el proyecto con el que estaba teniendo este problema. If I remember correctly, I downgraded react-native to "solve' the problem. Si no recuerdo mal, bajé la categoría de react-native para "resolver" el problema.

en

Experiencing the same issue, has there been a fix yet? Experimentando el mismo problema, ¿ha habido una solución todavía? Anyone find any workarounds to implementing sockets in React Native? ¿Alguien encontró alguna solución para implementar sockets en React Native?

en

@russellgoldman I had problems with RN 0.60.5 and socket.io. @russellgoldman Tuve problemas con RN 0.60.5 y socket.io. Release build did not connect to the server. La compilación de la versión no se conectó al servidor.

None of socket.io versions worked with RN 0.60.5: I tried versions 2.0.4, 2.1.1, 2.2.0. Ninguna de las versiones de socket.io funcionó con RN 0.60.5: probé las versiones 2.0.4, 2.1.1, 2.2.0.

Downgrading to RN 0.59.10 solved my problem. Bajar de categoría a RN 0.59.10 resolvió mi problema.

en

Hi @anttirauh and @russellgoldman , Hola @anttirauh y @russellgoldman ,
I tried with RN 0.59.10 and Socket 2.0.4, but its not connecting on release build. Probé con RN 0.59.10 y Socket 2.0.4, pero no se conecta en la versión de lanzamiento.
Can you please help me? ¿Podrías ayudarme?

en

@ Ramesh21071993 Creo que debe actualizar socket.io a la versión 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 , probé con todas estas versiones socket io (2.0.4, 2.1.1, 2.2.0) y versiones nativas de reacción (0.60, 0.59.10, 0.59.4)
In server side also socket io 2.0.4. En el lado del servidor también socket io 2.0.4.
still that same issue sir, sigue siendo el mismo problema señor,

But it works on RN 0.55.4 Pero funciona en RN 0.55.4

en

@Ramesh21071993 My understanding (which is formed with heavy googling and own testing) is that: @ Ramesh21071993 Según tengo entendido (que se forma con muchas búsquedas en Google y pruebas propias) es que:

  • socket.io stopped working with react-native about around RN version 0.57.4 socket.io dejó de funcionar con react-native alrededor de la versión 0.57.4 de RN
  • 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 o algún otro componente se arregló más tarde y logré hacerlo funcionar con la versión combinada: RN 0.59.10 + socket.io 2.1.1
  • RN version 0.60.x is not working with any version of socket.io La versión 0.60.x de RN no funciona con ninguna versión 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. Entonces, mi consejo es solo: intente una vez más con RN 0.59.10 y socket.io 2.1.1 y asegúrese de borrar la carpeta de compilación antes de compilar. And remove node_modules before yarn/npm. Y elimine node_modules antes de yarn/npm.

en

@anttirauh Sir, below is my package.json. @anttirauh Señor, a continuación se muestra mi paquete.json. I did as what you told. Hice como me dijiste. But nothing happen. Pero no pasa nada. I remove build folder and node modules and again i install. Elimino la carpeta de compilación y los módulos de nodo y nuevamente instalo.
Please help me on this to work, Past one month am trying Por favor, ayúdenme a que esto funcione. Hace un mes que estoy intentando.

App package.json Paquete de aplicación.json

{ {
"name": "Track", "nombre": "Pista",
"version": "0.0.1", "versión": "0.0.1",
"private": true, "privado": cierto,
"scripts": { "guiones": {
"start": "node node_modules/react-native/local-cli/cli.js start", "inicio": "nodo node_modules/react-native/local-cli/cli.js start",
"test": "jest" "prueba": "broma"
}, },
"dependencies": { "dependencias": {
"react": "16.8.3", "reaccionar": "16.8.3",
"react-native": "0.59.10", "reaccionar nativo": "0.59.10",
"socket.io": "2.1.1" "socket.io": "2.1.1"
}, },
"devDependencies": { "Dependencias de desarrollo": {
"@babel/core": "^7.6.2", "@babel/core": "^7.6.2",
"@babel/runtime": "^7.6.2", "@babel/tiempo de ejecución": "^7.6.2",
"babel-jest": "^24.9.0", "babel-jest": "^24.9.0",
"jest": "^24.9.0", "broma": "^24.9.0",
"metro-react-native-babel-preset": "^0.56.0", "metro-reaccionar-native-babel-preset": "^0.56.0",
"react-test-renderer": "16.8.3" "reaccionar-prueba-procesador": "16.8.3"
}, },
"jest": { "broma": {
"preset": "react-native" "preestablecido": "reaccionar nativo"
} }
} }

Server Package.json Paquete de servidor.json

{ {
"name": "TRACK-Socket", "nombre": "Socket de PISTA",
"version": "0.0.1", "versión": "0.0.1",
"dependencies": { "dependencias": {
"amqplib": "^0.5.1", "amqplib": "^0.5.1",
"config": "^3.2.2", "config": "^3.2.2",
"express": "^4.15.3", "expreso": "^4.15.3",
"socket.io": "^2.1.1", "socket.io": "^2.1.1",
"ws": "^7.1.2" "ws": "^7.1.2"
} }
} }

Thanks Gracias

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. Finalmente , encontré una solución para React Native> = 0.60 después de un par de cafés y profundizando en engine.io; además de un conflicto de versión (con RN), parece haber un problema al pasar el URI. When I pass an URI into socketIO, it gets turncated to the host and 'socket.io' appened. Cuando paso un URI a socketIO, se conecta al host y se agrega 'socket.io'. 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. Por lo tanto socketIO("https://foo.bar/my/endpoint/socket.io") hará que socketIO intente conectarse a https://foo.bar/socket.io sin mostrarlo en los registros al arrojar el error xhr pull/socket.

Here we go, how to get socket.io running on current versions of React Native : Aquí vamos, cómo hacer que socket.io se ejecute en las versiones actuales de React Native :

  • use socket.io-client version _2.1.1_ usar socket.io-client versión _2.1.1_
// package.json
{
  "dependencies": {
     "socket.io-client": "2.1.1"
   }
}
  • when setting up the client, define a host and a path al configurar el cliente, defina un host y una ruta
const socket = socketIO('https://your.host.com/', {
  path: '/path/to/socket.io/'
})
  • and suddenly everything works as smooth as planed y de repente todo funciona tan bien como estaba planeado

Hope to have saved you the time I spent on this issue 😆 Espero haberles ahorrado el tiempo que dediqué a este tema 😆

en

@rastapasta , i got an error like “ CLEARTEXT communication not permitted by network security policy ”, @rastapasta , recibí un error como " Comunicación CLEARTEXT no permitida por la política de seguridad de la red ",

Please tell me what to do Por favor dime qué hacer

en

@Ramesh21071993 if you can't use your endpoint via https (please consider it), add their hostnames to the exception lists. @ Ramesh21071993 si no puede usar su punto final a través de https (considérelo), agregue sus nombres de host a las listas de excepciones.

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

en

Sir, I tried that also but not able to do. Señor, también lo intenté pero no pude hacerlo. If you don't mind can you please give me any demo source files Si no le importa, ¿puede darme algún archivo fuente de demostración?
For long time I struck with this. Durante mucho tiempo golpeé con esto.

Am using ip and port sir Estoy usando ip y puerto señor

en

siga las instrucciones de las documentaciones anteriores y adapte esta implementación:

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

Señor, en el lado del servidor estoy usando socket io 2.1.1, ¿está bien o hay que cambiar algo?

en

image

en

@Lizhooh forma ingeniosa de descubrir whazzup en rn: mono parchea un console.log(err) antes del self.onError en su node_modules engine.io-client/blob/master/lib/transports/ sondeo-xhr.js #L131

en

@Ramesh21071993 Is your issue resolved? @ Ramesh21071993 ¿Se resolvió su problema? I am facing the same issue. Estoy enfrentando el mismo problema. Tried everything mentioned in above comments. Intenté todo lo mencionado en los comentarios anteriores.

en

@rastapasta I followed what you have suggested above. @rastapasta Seguí lo que sugirió anteriormente. My socket connection happens and then immediately disconnects. Mi conexión de socket ocurre y luego se desconecta inmediatamente. I get timeout error infinitely. Recibo un error de tiempo de espera infinitamente. However, whenever I click on some component which makes a network call, the socket connects and immediately disconnects. Sin embargo, cada vez que hago clic en algún componente que realiza una llamada de red, el enchufe se conecta y se desconecta inmediatamente. If I don't do any network call after first socket disconnect, it would stay in the same state. Si no hago ninguna llamada de red después de la primera desconexión del enchufe, permanecerá en el mismo estado. Please, could you help? Por favor, ¿podrías ayudar?

socket = io('http://IP:31515', { enchufe = 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 ruta: '/socketio', //He dado esta es la ruta en mi servidor de socket, así como mi archivo de entrada de kubernetes para enrutar a ese puerto
transports: ['websocket'], transportes: ['websocket'],
reconnectionDelay: 1000, reconexiónRetraso: 1000,
reconnection: true, reconexión: cierto,
reconnectionAttempts: Infinity, intentos de reconexión: infinito,
// timeout: 30000, // tiempo de espera: 30000,
jsonp: false jsonp: falso
}); });

things that I have tried: cosas que he probado:

  1. removing and adding transports option eliminando y agregando la opción de transportes
    2.removing and add timeout 2.eliminar y agregar tiempo de espera
  2. removing all parameters except path eliminando todos los parámetros excepto la ruta
  3. adding pingTimeout and pingInterval in server socket configuration agregando pingTimeout y pingInterval en la configuración del socket del servidor
  4. removing path from server and client and only keeping it in my kubernetes ingress file to route to that deployment/pod. eliminando la ruta del servidor y el cliente y solo manteniéndola en mi archivo de entrada de kubernetes para enrutar a esa implementación/pod.

Note: the same server and kubernetes conf work for any node.js socket client as well as my react js web app. Nota: el mismo servidor y kubernetes conf funcionan para cualquier cliente de socket node.js, así como para mi aplicación web react js. I am only facing this issue for React Native app in debug as well as release mode. Solo enfrento este problema para la aplicación React Native en modo de depuración y lanzamiento.

en

¿Alguien tiene alguna idea para mi problema anterior?

en

@calqlum123 @calqlum123
Please make sure to Por favor, asegúrese de

  • add your host to the transport exception list (s. here ) agregue su host a la lista de excepciones de transporte ( ver aquí )
  • try it without manually defining the transports probarlo sin definir manualmente los transportes
  • monkey patch the console.log (s. here ) and check the error monkey parche the console.log (s. aquí ) y verifique el error
en

Can anyone please share a complete working example for both client and server? ¿Alguien puede compartir un ejemplo de trabajo completo tanto para el cliente como para el servidor? Because this is confusing. Porque esto es confuso.

en

I am using "react-native": "0.61.5" and "socket.io-client": "^2.1.1", Estoy usando "react-native": "0.61.5" y "socket.io-client": "^2.1.1",

below is my code a continuación está mi código

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. El código no puede conectarse al servidor y también estoy buscando la solución. I don't want to downgrade my react-native version. No quiero degradar mi versión nativa de reacción.

en

you must add this code in application tag debe agregar este código en la etiqueta de la aplicación
like below in AndroidManifest.xml como a continuación en AndroidManifest.xml
. . . . . .

en

I am using "react-native": "0.61.5" and "socket.io-client": "^2.1.1", Estoy usando "react-native": "0.61.5" y "socket.io-client": "^2.1.1",

below is my code a continuación está mi código

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. El código no puede conectarse al servidor y también estoy buscando la solución. I don't want to downgrade my react-native version. No quiero degradar mi versión nativa de reacción.

Can you try "ws://192.168.0.101:1234", instead of " http://192.168.0.101 :1234" ¿Puede probar "ws://192.168.0.101:1234", en lugar de " http://192.168.0.101:1234 "?

en

@Unforgiven-wanda se ha agregado un ejemplo con React Native aquí: https://github.com/socketio/socket.io/tree/master/examples/react-native

en

No se puede conectar con "socket.io-client": "^3.0.4" en reaccionar nativo

en

@chiragpurohit71085 have you checked the example there: https://github.com/socketio/socket.io/tree/master/examples/react-native? @ chiragpurohit71085 , ¿ha revisado el ejemplo allí: 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 ? Creo que se trata de un problema de URL, ¿podría verificar si se puede acceder a su servidor en http://192.168.x.y:z ?

en
¿Fue útil esta página
0 / 5 - 0 calificaciones