Socket.io-client: Не удается подключиться через socket.io-client на react-native

Созданный на 31 окт. 2018  ·  37Комментарии  ·  Источник: socketio/socket.io-client

You want to: Вы хотите:

  • [x] report a bug [x] сообщить об ошибке
  • [ ] request a feature [ ] запросить функцию

Current behaviour Текущее поведение

I can't connect via socket io to my server, it times out. Я не могу подключиться через сокет io к своему серверу, время ожидания истекло.

Steps to reproduce (if the current behaviour is a bug) Шаги для воспроизведения (если текущее поведение является ошибкой)

In 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: Журналы отладки выглядят так:

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 . Примечание : лучший способ (и под этим мы подразумеваем единственный способ ) получить быстрый ответ — предоставить неудавшийся тестовый пример, разветвив следующую скрипку .

Expected behaviour Ожидаемое поведение

I expect to be able to connect to my socketio server, the same way I am able to in a web browser. Я ожидаю, что смогу подключиться к моему серверу socketio так же, как в веб-браузере.

Setup Настраивать

  • OS: iOS iPhone 10 simulator ОС: iOS симулятор iPhone 10
  • browser: React-native браузер: React-native
  • socket.io version: 2.1.1 версия socket.io: 2.1.1
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. Наконец -то нашел решение для React Native >= 0.60 после пары чашек кофе и глубокого копания в engine.io - в дополнение к конфликту версий (с RN), похоже, есть проблема с передачей URI. When I pass an URI into socketIO, it gets turncated to the host and 'socket.io' appened. Когда я передаю URI в socketIO, он перенаправляется на хост и добавляется «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. Таким образом, socketIO("https://foo.bar/my/endpoint/socket.io") приведет к тому, что socketIO попытается подключиться к https://foo.bar/socket.io , не отображая его в журналах при выдаче ошибки xhr pull/socket.

Here we go, how to get socket.io running on current versions of React Native : Итак, начнем с того, как запустить socket.io в текущих версиях React Native :

  • use socket.io-client version _2.1.1_ используйте версию socket.io-client _2.1.1_
// package.json
{
  "dependencies": {
     "socket.io-client": "2.1.1"
   }
}
  • when setting up the client, define a host and a path при настройке клиента укажите хост и путь
const socket = socketIO('https://your.host.com/', {
  path: '/path/to/socket.io/'
})
  • and suddenly everything works as smooth as planed и вдруг все работает как положено

Hope to have saved you the time I spent on this issue 😆 Надеюсь, что сэкономил вам время, потраченное на этот вопрос 😆

en

Все 37 Комментарий

Looks like this is react-native's issue. Похоже, это проблема реактивного натива. Earlier versions of RN seem to work with socket.io, but 0.0.57 does not. Более ранние версии RN работают с socket.io, а 0.0.57 — нет. Closing. Закрытие.

en

Try "socket.io-client": "2.0.4" Попробуйте "socket.io-client": "2.0.4"
This may be socket.io bug Это может быть ошибка socket.io

en

Try "socket.io-client": "2.0.4" Попробуйте "socket.io-client": "2.0.4"
This may be socket.io bug Это может быть ошибка socket.io

Yes it does work. Да, это работает.

en

С RN 0.52 и socket.io-client 2.0.4 я все еще сталкиваюсь с этой проблемой.

en

@noahprince22 can you please share your configuration ? @ noahprince22 , не могли бы вы поделиться своей конфигурацией?
I am currently using this and the issue still persist. Я в настоящее время использую это, и проблема все еще сохраняется.

"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? любой обходной путь?

socket.io team please, this should work with RN, is a socket.io bug. Команда socket.io, пожалуйста, это должно работать с RN, это ошибка socket.io.

en

Hi @ningacoding , I managed to get it working with this configuration Привет @ningacoding , мне удалось заставить его работать с этой конфигурацией

"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 В своем родном приложении используйте это

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

"react-native": "0.58.6", "реагировать-родной": "0.58.6",
"react": "16.6.3", «реагировать»: «16.6.3»,
"socket.io-client": "^2.0.4", "socket.io-клиент": "^2.0.4",

Not working for me Не работает для меня

en

any solution? любое решение? I'm facing the same thing я столкнулся с тем же

en

I have long since stopped working on the project that I was having this issue with. Я давно перестал работать над проектом, с которым у меня была эта проблема. If I remember correctly, I downgraded react-native to "solve' the problem. Если я правильно помню, я понизил версию react-native, чтобы «решить» проблему.

en

Experiencing the same issue, has there been a fix yet? Столкнулся с такой же проблемой, есть решение? Anyone find any workarounds to implementing sockets in React Native? Кто-нибудь нашел обходные пути для реализации сокетов в React Native?

en

@russellgoldman I had problems with RN 0.60.5 and socket.io. @russellgoldman У меня были проблемы с RN 0.60.5 и socket.io. Release build did not connect to the server. Релизная сборка не подключилась к серверу.

None of socket.io versions worked with RN 0.60.5: I tried versions 2.0.4, 2.1.1, 2.2.0. Ни одна из версий socket.io не работала с RN 0.60.5: пробовал версии 2.0.4, 2.1.1, 2.2.0.

Downgrading to RN 0.59.10 solved my problem. Переход на RN 0.59.10 решил мою проблему.

en

Hi @anttirauh and @russellgoldman , Привет @anttirauh и @russellgoldman ,
I tried with RN 0.59.10 and Socket 2.0.4, but its not connecting on release build. Я пробовал с RN 0.59.10 и Socket 2.0.4, но он не подключается к сборке релиза.
Can you please help me? Не могли бы вы мне помочь?

en

@ Ramesh21071993 Я думаю, вы должны обновить socket.io до версии 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 , я пробовал со всеми этими версиями сокета io (2.0.4, 2.1.1, 2.2.0) и реактивными версиями (0.60, 0.59.10, 0.59.4)
In server side also socket io 2.0.4. На стороне сервера также сокет io 2.0.4.
still that same issue sir, все та же проблема, сэр,

But it works on RN 0.55.4 Но работает на РН 0.55.4

en

@Ramesh21071993 My understanding (which is formed with heavy googling and own testing) is that: @Ramesh21071993 Ramesh21071993 Мое понимание (которое сформировалось в результате тщательного поиска в Google и собственного тестирования) таково:

  • socket.io stopped working with react-native about around RN version 0.57.4 socket.io перестал работать с react-native примерно в версии 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 или какой-либо другой компонент был исправлен позже, и мне удалось заставить его работать с комбинацией версий: RN 0.59.10 + socket.io 2.1.1
  • RN version 0.60.x is not working with any version of socket.io RN версии 0.60.x не работает ни с одной версией 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. Поэтому мой совет: попробуйте еще раз с RN 0.59.10 и socket.io 2.1.1 и убедитесь, что вы очистили папку сборки перед сборкой. And remove node_modules before yarn/npm. И удалите node_modules перед пряжей/npm.

en

@anttirauh Sir, below is my package.json. @anttirauh Сэр, ниже мой package.json. I did as what you told. Я сделал так, как ты сказал. But nothing happen. Но ничего не происходит. I remove build folder and node modules and again i install. Я удаляю папку сборки и модули узла и снова устанавливаю.
Please help me on this to work, Past one month am trying Пожалуйста, помогите мне в этом, чтобы работать, последний месяц я пытаюсь

App package.json Пакет приложения.json

{ {
"name": "Track", "имя": "Трек",
"version": "0.0.1", "версия": "0.0.1",
"private": true, "частное": правда,
"scripts": { "скрипты": {
"start": "node node_modules/react-native/local-cli/cli.js start", "start": "запуск узла node_modules/react-native/local-cli/cli.js",
"test": "jest" "тест": "шутка"
}, },
"dependencies": { "зависимости": {
"react": "16.8.3", «реагировать»: «16.8.3»,
"react-native": "0.59.10", "реагировать-родной": "0.59.10",
"socket.io": "2.1.1" "сокет.ио": "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", "вавилонская шутка": "^24.9.0",
"jest": "^24.9.0", "шутка": "^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" "реакция-тест-рендерер": "16.8.3"
}, },
"jest": { "шутка": {
"preset": "react-native" "предустановка": "реагировать-родной"
} }
} }

Server Package.json Пакет сервера.json

{ {
"name": "TRACK-Socket", "имя": "TRACK-Socket",
"version": "0.0.1", "версия": "0.0.1",
"dependencies": { "зависимости": {
"amqplib": "^0.5.1", "amqplib": "^0.5.1",
"config": "^3.2.2", "config": "^3.2.2",
"express": "^4.15.3", "экспресс": "^4.15.3",
"socket.io": "^2.1.1", "сокет.ио": "^2.1.1",
"ws": "^7.1.2" "вс": "^7.1.2"
} }
} }

Thanks Спасибо

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. Наконец -то нашел решение для React Native >= 0.60 после пары чашек кофе и глубокого копания в engine.io - в дополнение к конфликту версий (с RN), похоже, есть проблема с передачей URI. When I pass an URI into socketIO, it gets turncated to the host and 'socket.io' appened. Когда я передаю URI в socketIO, он перенаправляется на хост и добавляется «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. Таким образом, socketIO("https://foo.bar/my/endpoint/socket.io") приведет к тому, что socketIO попытается подключиться к https://foo.bar/socket.io , не отображая его в журналах при выдаче ошибки xhr pull/socket.

Here we go, how to get socket.io running on current versions of React Native : Итак, начнем с того, как запустить socket.io в текущих версиях React Native :

  • use socket.io-client version _2.1.1_ используйте версию socket.io-client _2.1.1_
// package.json
{
  "dependencies": {
     "socket.io-client": "2.1.1"
   }
}
  • when setting up the client, define a host and a path при настройке клиента укажите хост и путь
const socket = socketIO('https://your.host.com/', {
  path: '/path/to/socket.io/'
})
  • and suddenly everything works as smooth as planed и вдруг все работает как положено

Hope to have saved you the time I spent on this issue 😆 Надеюсь, что сэкономил вам время, потраченное на этот вопрос 😆

en

@rastapasta , i got an error like “ CLEARTEXT communication not permitted by network security policy ”, @rastapasta , я получил сообщение об ошибке типа « Связь CLEARTEXT не разрешена политикой сетевой безопасности »,

Please tell me what to do Пожалуйста, скажите мне, что делать

en

@Ramesh21071993 if you can't use your endpoint via https (please consider it), add their hostnames to the exception lists. @ Ramesh21071993 Ramesh21071993 , если вы не можете использовать свою конечную точку через https (пожалуйста, учтите это), добавьте их имена хостов в списки исключений.

for iOS: https://stackoverflow.com/a/30732693 для iOS: https://stackoverflow.com/a/30732693
for Android: https://stackoverflow.com/a/50834600 для Android: https://stackoverflow.com/a/50834600

en

Sir, I tried that also but not able to do. Сэр, я тоже пробовал, но не смог. If you don't mind can you please give me any demo source files Если вы не возражаете, не могли бы вы дать мне любые исходные файлы демо
For long time I struck with this. Давно я этим заморачивался.

Am using ip and port sir Я использую ip и порт, сэр.

en

следуйте указаниям приведенной выше документации и адаптируйте эту реализацию:

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

Сэр, на стороне сервера я использую сокет io 2.1.1, все в порядке или нужно что-то изменить?

en

image

en

@Lizhooh хакерский способ узнать whazzup на rn: обезьяна исправит console.log(err) перед self.onError в вашем node_modules engine.io-client/blob/master/lib/transports/ опрос-xhr.js # L131

en

@Ramesh21071993 Is your issue resolved? @ Ramesh21071993 Ваша проблема решена? I am facing the same issue. Я столкнулся с той же проблемой. Tried everything mentioned in above comments. Пробовал все, что указано в комментариях выше.

en

@rastapasta I followed what you have suggested above. @rastapasta Я следовал тому, что вы предложили выше. My socket connection happens and then immediately disconnects. Мое подключение к сокету происходит, а затем сразу же отключается. I get timeout error infinitely. Я получаю ошибку тайм-аута бесконечно. However, whenever I click on some component which makes a network call, the socket connects and immediately disconnects. Однако всякий раз, когда я нажимаю на какой-либо компонент, который выполняет сетевой вызов, сокет подключается и сразу же отключается. If I don't do any network call after first socket disconnect, it would stay in the same state. Если я не сделаю никакого сетевого вызова после первого отключения сокета, он останется в том же состоянии. Please, could you help? Пожалуйста, не могли бы вы помочь?

socket = io('http://IP:31515', { сокет = 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', // я указал это путь на моем сервере сокетов, а также мой входной файл kubernetes для маршрутизации на этот порт
transports: ['websocket'], транспорты: ['websocket'],
reconnectionDelay: 1000, задержка переподключения: 1000,
reconnection: true, переподключение: правда,
reconnectionAttempts: Infinity, попытки повторного подключения: бесконечность,
// timeout: 30000, // время ожидания: 30000,
jsonp: false jsonp: ложь
}); });

things that I have tried: вещи, которые я пробовал:

  1. removing and adding transports option удаление и добавление опции транспорта
    2.removing and add timeout 2.удаление и добавление таймаута
  2. removing all parameters except path удаление всех параметров кроме пути
  3. adding pingTimeout and pingInterval in server socket configuration добавление pingTimeout и pingInterval в конфигурацию сокета сервера
  4. removing path from server and client and only keeping it in my kubernetes ingress file to route to that deployment/pod. удаление пути с сервера и клиента и сохранение его только в моем входном файле kubernetes для маршрутизации к этому развертыванию/модулю.

Note: the same server and kubernetes conf work for any node.js socket client as well as my react js web app. Примечание: один и тот же сервер и конфигурация kubernetes работают для любого клиента сокета node.js, а также для моего веб-приложения react js. I am only facing this issue for React Native app in debug as well as release mode. Я сталкиваюсь с этой проблемой только для приложения React Native как в режиме отладки, так и в режиме выпуска.

en

У кого-нибудь есть идеи по моей вышеуказанной проблеме?

en

@calqlum123 @calqlum123
Please make sure to Пожалуйста, убедитесь, что

  • add your host to the transport exception list (s. here ) добавьте свой хост в список исключений транспорта (см. здесь )
  • try it without manually defining the transports попробуйте без ручного определения транспортов
  • monkey patch the console.log (s. here ) and check the error обезьяна патчит console.log (см. здесь ) и проверяет ошибку
en

Can anyone please share a complete working example for both client and server? Может ли кто-нибудь поделиться полным рабочим примером для клиента и сервера? Because this is confusing. Потому что это сбивает с толку.

en

I am using "react-native": "0.61.5" and "socket.io-client": "^2.1.1", Я использую "react-native": "0.61.5" и "socket.io-client": "^2.1.1",

below is my 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. Код не может подключиться к серверу, и я также ищу решение. I don't want to downgrade my react-native version. Я не хочу понижать версию своей реактивной версии.

en

you must add this code in application tag вы должны добавить этот код в тег приложения
like below in AndroidManifest.xml как показано ниже в AndroidManifest.xml
. . . . . .

en

I am using "react-native": "0.61.5" and "socket.io-client": "^2.1.1", Я использую "react-native": "0.61.5" и "socket.io-client": "^2.1.1",

below is my 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. Код не может подключиться к серверу, и я также ищу решение. I don't want to downgrade my react-native version. Я не хочу понижать версию своей реактивной версии.

Can you try "ws://192.168.0.101:1234", instead of " http://192.168.0.101 :1234" Можете попробовать "ws://192.168.0.101:1234" вместо " http://192.168.0.101:1234 "

en

@Unforgiven-wanda здесь добавлен пример с React Native: https://github.com/socketio/socket.io/tree/master/examples/react-native

en

Не удалось подключиться к «socket.io-client»: «^ 3.0.4» в реакции на родной

en

@chiragpurohit71085 have you checked the example there: https://github.com/socketio/socket.io/tree/master/examples/react-native? @chiragpurohit71085 вы проверили пример: 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 ? Я думаю, что это проблема URL-адреса. Не могли бы вы проверить, доступен ли ваш сервер по адресу http://192.168.x.y:z ?

en
Была ли эта страница полезной?
0 / 5 - 0 рейтинги