Socket.io-client: Não é possível conectar via socket.io-client em react-native

Criado em 31 out. 2018  ·  37Comentários  ·  Fonte: socketio/socket.io-client

You want to: Você quer:

  • [x] report a bug [x] reportar um bug
  • [ ] request a feature [ ] solicitar um recurso

Current behaviour Comportamento atual

I can't connect via socket io to my server, it times out. Não consigo conectar via soquete io ao meu servidor, ele expira.

Steps to reproduce (if the current behaviour is a bug) Etapas para reproduzir (se o comportamento atual for um bug)

In react-native: Em react-native:

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: Os logs de depuração se parecem com:

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 : a melhor maneira (e com isso queremos dizer a única maneira ) de obter uma resposta rápida é fornecer um caso de teste com falha, bifurcando o seguinte violino .

Expected behaviour Comportamento 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 me conectar ao meu servidor socketio, da mesma forma que consigo em um navegador da web.

Setup Configuração

  • OS: iOS iPhone 10 simulator SO: simulador iOS iPhone 10
  • browser: React-native navegador: React-native
  • socket.io version: 2.1.1 versão do socket.io: 2.1.1
en

Comentários muito úteis

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 encontrei uma solução para React Native >= 0,60 depois de alguns cafés e cavando fundo no engine.io - além de um conflito de versão (com RN), parece haver um problema com a passagem do URI. When I pass an URI into socketIO, it gets turncated to the host and 'socket.io' appened. Quando eu passo um URI no socketIO, ele é ativado para o host e 'socket.io' é anexado. 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. Portanto socketIO("https://foo.bar/my/endpoint/socket.io") levará o socketIO a tentar se conectar a https://foo.bar/socket.io sem mostrá-lo nos logs ao lançar o erro xhr pull / socket.

Here we go, how to get socket.io running on current versions of React Native : Aqui vamos nós, como fazer o socket.io rodar nas versões atuais do React Native :

  • use socket.io-client version _2.1.1_ use socket.io-client versão _2.1.1_
// package.json
{
  "dependencies": {
     "socket.io-client": "2.1.1"
   }
}
  • when setting up the client, define a host and a path ao configurar o cliente, defina um host e um caminho
const socket = socketIO('https://your.host.com/', {
  path: '/path/to/socket.io/'
})
  • and suddenly everything works as smooth as planed e de repente tudo funciona tão bem quanto planejado

Hope to have saved you the time I spent on this issue 😆 Espero ter poupado o tempo que dediquei a esta questão 😆

en

Todos 37 comentários

Looks like this is react-native's issue. Parece que este é um problema do react-native. Earlier versions of RN seem to work with socket.io, but 0.0.57 does not. Versões anteriores do RN parecem funcionar com socket.io, mas 0.0.57 não. Closing. Fechamento.

en

Try "socket.io-client": "2.0.4" Tente "socket.io-client": "2.0.4"
This may be socket.io bug Isso pode ser um bug do socket.io

en

Try "socket.io-client": "2.0.4" Tente "socket.io-client": "2.0.4"
This may be socket.io bug Isso pode ser um bug do socket.io

Yes it does work. Sim funciona.

en

Com RN 0.52 e socket.io-client 2.0.4 ainda estou enfrentando esse problema.

en

@noahprince22 can you please share your configuration ? @noahprince22 você pode compartilhar sua configuração?
I am currently using this and the issue still persist. Atualmente estou usando isso e o problema ainda 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? alguma solução alternativa?

socket.io team please, this should work with RN, is a socket.io bug. equipe socket.io por favor, isso deve funcionar com RN, é um bug socket.io.

en

Hi @ningacoding , I managed to get it working with this configuration Oi @ningacoding , consegui fazê-lo funcionar com esta configuração

"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 Em seu aplicativo nativo de reação, use isso

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

"react-native": "0.58.6", "react-native": "0.58.6",
"react": "16.6.3", "reagir": "16.6.3",
"socket.io-client": "^2.0.4", "socket.io-client": "^2.0.4",

Not working for me Não está funcionando para mim

en

any solution? qualquer solução? I'm facing the same thing estou enfrentando a mesma coisa

en

I have long since stopped working on the project that I was having this issue with. Há muito tempo parei de trabalhar no projeto com o qual estava tendo esse problema. If I remember correctly, I downgraded react-native to "solve' the problem. Se bem me lembro, fiz o downgrade do react-native para "resolver" o problema.

en

Experiencing the same issue, has there been a fix yet? Tendo o mesmo problema, já houve uma correção? Anyone find any workarounds to implementing sockets in React Native? Alguém encontrou alguma solução alternativa para implementar soquetes no React Native?

en

@russellgoldman I had problems with RN 0.60.5 and socket.io. @russellgoldman Tive problemas com RN 0.60.5 e socket.io. Release build did not connect to the server. A compilação da versão não se conectou ao servidor.

None of socket.io versions worked with RN 0.60.5: I tried versions 2.0.4, 2.1.1, 2.2.0. Nenhuma das versões do socket.io funcionou com o RN 0.60.5: tentei as versões 2.0.4, 2.1.1, 2.2.0.

Downgrading to RN 0.59.10 solved my problem. Fazer downgrade para RN 0.59.10 resolveu meu problema.

en

Hi @anttirauh and @russellgoldman , Olá @anttirauh e @russellgoldman ,
I tried with RN 0.59.10 and Socket 2.0.4, but its not connecting on release build. Eu tentei com RN 0.59.10 e Socket 2.0.4, mas não está conectando na compilação de lançamento.
Can you please help me? Você pode por favor me ajudar?

en

@ Ramesh21071993 Acho que você deve atualizar o socket.io para a versão 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 , eu tentei com todas essas versões socket io (2.0.4, 2.1.1, 2.2.0) e versões nativas de reação (0.60, 0.59.10, 0.59.4)
In server side also socket io 2.0.4. No lado do servidor também socket io 2.0.4.
still that same issue sir, continua com o mesmo problema senhor

But it works on RN 0.55.4 Mas funciona em RN 0.55.4

en

@Ramesh21071993 My understanding (which is formed with heavy googling and own testing) is that: @ Ramesh21071993 Meu entendimento (que é formado com pesquisa pesada e testes próprios) é que:

  • socket.io stopped working with react-native about around RN version 0.57.4 socket.io parou de funcionar com react-native por volta da versão 0.57.4 do 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 ou algum outro componente foi corrigido mais tarde e consegui fazê-lo funcionar com a versão combo: RN 0.59.10 + socket.io 2.1.1
  • RN version 0.60.x is not working with any version of socket.io RN versão 0.60.x não está funcionando com nenhuma versão do 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. Portanto, meu conselho é apenas: tente mais uma vez com RN 0.59.10 e socket.io 2.1.1 e certifique-se de limpar a pasta de compilação antes de compilar. And remove node_modules before yarn/npm. E remova node_modules antes de yarn/npm.

en

@anttirauh Sir, below is my package.json. @anttirauh Senhor, abaixo está meu package.json. I did as what you told. Fiz como você disse. But nothing happen. Mas nada acontece. I remove build folder and node modules and again i install. Eu removo a pasta de compilação e os módulos do nó e novamente instalo.
Please help me on this to work, Past one month am trying Por favor me ajude nisso para trabalhar, passado um mês estou tentando

App package.json Pacote de aplicativos.json

{ {
"name": "Track", "nome": "Faixa",
"version": "0.0.1", "versão": "0.0.1",
"private": true, "privado": verdadeiro,
"scripts": { "roteiros": {
"start": "node node_modules/react-native/local-cli/cli.js start", "start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest" "teste": "brincadeira"
}, },
"dependencies": { "dependências": {
"react": "16.8.3", "reagir": "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", "brincadeira": "^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": { "brincadeira": {
"preset": "react-native" "preset": "react-native"
} }
} }

Server Package.json Pacote do servidor.json

{ {
"name": "TRACK-Socket", "name": "TRACK-Socket",
"version": "0.0.1", "versão": "0.0.1",
"dependencies": { "dependências": {
"amqplib": "^0.5.1", "amqplib": "^0.5.1",
"config": "^3.2.2", "config": "^3.2.2",
"express": "^4.15.3", "expresso": "^4.15.3",
"socket.io": "^2.1.1", "socket.io": "^2.1.1",
"ws": "^7.1.2" "ws": "^7.1.2"
} }
} }

Thanks Obrigado

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 encontrei uma solução para React Native >= 0,60 depois de alguns cafés e cavando fundo no engine.io - além de um conflito de versão (com RN), parece haver um problema com a passagem do URI. When I pass an URI into socketIO, it gets turncated to the host and 'socket.io' appened. Quando eu passo um URI no socketIO, ele é ativado para o host e 'socket.io' é anexado. 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. Portanto socketIO("https://foo.bar/my/endpoint/socket.io") levará o socketIO a tentar se conectar a https://foo.bar/socket.io sem mostrá-lo nos logs ao lançar o erro xhr pull / socket.

Here we go, how to get socket.io running on current versions of React Native : Aqui vamos nós, como fazer o socket.io rodar nas versões atuais do React Native :

  • use socket.io-client version _2.1.1_ use socket.io-client versão _2.1.1_
// package.json
{
  "dependencies": {
     "socket.io-client": "2.1.1"
   }
}
  • when setting up the client, define a host and a path ao configurar o cliente, defina um host e um caminho
const socket = socketIO('https://your.host.com/', {
  path: '/path/to/socket.io/'
})
  • and suddenly everything works as smooth as planed e de repente tudo funciona tão bem quanto planejado

Hope to have saved you the time I spent on this issue 😆 Espero ter poupado o tempo que dediquei a esta questão 😆

en

@rastapasta , i got an error like “ CLEARTEXT communication not permitted by network security policy ”, @rastapasta , recebi um erro como “ comunicação CLEARTEXT não permitida pela política de segurança de rede ”,

Please tell me what to do Por favor me diga o que fazer

en

@Ramesh21071993 if you can't use your endpoint via https (please consider it), add their hostnames to the exception lists. @Ramesh21071993 se você não puder usar seu endpoint via https (por favor, considere), adicione seus nomes de host às listas de exceção.

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. Senhor, eu tentei isso também, mas não consegui. If you don't mind can you please give me any demo source files Se você não se importa, você pode me dar algum arquivo de origem de demonstração
For long time I struck with this. Por muito tempo eu bati com isso.

Am using ip and port sir Estou usando ip e porta senhor

en

siga as instruções das documentações acima e adapte esta implementação:

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

Senhor, no lado do servidor estou usando o socket io 2.1.1, tudo bem ou algo precisa mudar

en

image

en

@Lizhooh maneira hacky de descobrir o whazzup no rn: monkey patch a console.log(err) antes do self.onError no seu node_modules engine.io-client/blob/master/lib/transports/ polling-xhr.js #L131

en

@Ramesh21071993 Is your issue resolved? @Ramesh21071993 Seu problema foi resolvido? I am facing the same issue. Eu estou enfrentando o mesmo problema. Tried everything mentioned in above comments. Tentei tudo mencionado nos comentários acima.

en

@rastapasta I followed what you have suggested above. @rastapasta eu segui o que você sugeriu acima. My socket connection happens and then immediately disconnects. Minha conexão de soquete acontece e desconecta imediatamente. I get timeout error infinitely. Eu recebo erro de tempo limite infinitamente. However, whenever I click on some component which makes a network call, the socket connects and immediately disconnects. Porém, sempre que clico em algum componente que faz uma chamada de rede, o socket conecta e desconecta imediatamente. If I don't do any network call after first socket disconnect, it would stay in the same state. Se eu não fizer nenhuma chamada de rede após a primeira desconexão do soquete, ele permanecerá no mesmo estado. Please, could you help? Por favor, você poderia ajudar?

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', // Eu dei este é o caminho no meu servidor de soquete, bem como meu arquivo de entrada do kubernetes para rotear para essa porta
transports: ['websocket'], transportes: ['websocket'],
reconnectionDelay: 1000, Atraso de reconexão: 1000,
reconnection: true, reconexão: verdade,
reconnectionAttempts: Infinity, Tentativas de reconexão: Infinito,
// timeout: 30000, // tempo limite: 30000,
jsonp: false jsonp: falso
}); });

things that I have tried: coisas que eu tentei:

  1. removing and adding transports option opção de remoção e adição de transportes
    2.removing and add timeout 2. remover e adicionar tempo limite
  2. removing all parameters except path removendo todos os parâmetros, exceto o caminho
  3. adding pingTimeout and pingInterval in server socket configuration adicionando pingTimeout e pingInterval na configuração do soquete do servidor
  4. removing path from server and client and only keeping it in my kubernetes ingress file to route to that deployment/pod. removendo o caminho do servidor e do cliente e mantendo-o apenas no meu arquivo de entrada do kubernetes para rotear para essa implantação/pod.

Note: the same server and kubernetes conf work for any node.js socket client as well as my react js web app. Nota: o mesmo servidor e kubernetes conf funcionam para qualquer cliente de soquete node.js, bem como meu aplicativo web react js. I am only facing this issue for React Native app in debug as well as release mode. Estou enfrentando esse problema apenas para o aplicativo React Native no modo de depuração e no modo de lançamento.

en

Alguém tem alguma idéia para o meu problema acima?

en

@calqlum123 @calqlum123
Please make sure to Por favor, certifique-se de

  • add your host to the transport exception list (s. here ) adicione seu host à lista de exceções de transporte (s. aqui )
  • try it without manually defining the transports experimente sem definir manualmente os transportes
  • monkey patch the console.log (s. here ) and check the error macaco corrija o console.log (s. aqui ) e verifique o erro
en

Can anyone please share a complete working example for both client and server? Alguém pode compartilhar um exemplo completo de trabalho para cliente e servidor? Because this is confusing. Porque isso é confuso.

en

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

below is my code abaixo está meu 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. O código não consegue se conectar ao servidor e também estou procurando a solução. I don't want to downgrade my react-native version. Eu não quero fazer o downgrade da minha versão nativa de reação.

en

you must add this code in application tag você deve adicionar este código na tag do aplicativo
like below in AndroidManifest.xml como abaixo em AndroidManifest.xml
. . . . . .

en

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

below is my code abaixo está meu 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. O código não consegue se conectar ao servidor e também estou procurando a solução. I don't want to downgrade my react-native version. Eu não quero fazer o downgrade da minha versão nativa de reação.

Can you try "ws://192.168.0.101:1234", instead of " http://192.168.0.101 :1234" Você pode tentar "ws://192.168.0.101:1234", em vez de " http://192.168.0.101 :1234"

en

@Unforgiven-wanda um exemplo com React Native foi adicionado aqui: https://github.com/socketio/socket.io/tree/master/examples/react-native

en

Não é possível conectar com "socket.io-client": "^3.0.4" em reagir nativo

en

@chiragpurohit71085 have you checked the example there: https://github.com/socketio/socket.io/tree/master/examples/react-native? @chiragpurohit71085 você verificou o exemplo lá: 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 ? Eu acho que isso é um problema de URL, você poderia verificar se seu servidor está acessível em http://192.168.x.y:z ?

en
Esta página foi útil?
0 / 5 - 0 avaliações