React-native: Xcode 10 runtime warning on fresh install: nw_socket_handle_socket_event

Created on 10 Sep 2018  ·  104Comments  ·  Source: facebook/react-native

Description

While running the boilerplate react native app, I receive the runtime error:
2018-09-09 21:46:07.681496-0400 client[2035:560210] [] nw_socket_handle_socket_event [C6.2:1] Socket SO_ERROR [61: Connection refused] 2018-09-09 21:46:07.681861-0400 client[2035:560216] [] nw_connection_get_connected_socket [C6] Client called nw_connection_get_connected_socket on unconnected nw_connection 2018-09-09 21:46:07.681903-0400 client[2035:560216] TCP Conn 0x2821ac300 Failed : error 0:61 [61]
which loops over and over for the duration of debugging the app on a device. I'm not sure exactly what this error is associated with, however in my other app I receive the same error. This may or may not be related to remote push notifications (APNs).

Environment

React Native Environment Info: System: OS: macOS 10.14 CPU: x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz Memory: 27.59 MB / 16.00 GB Shell: 3.2.57 - /bin/bash Binaries: Node: 9.8.0 - /usr/local/bin/node Yarn: 1.5.1 - /usr/local/bin/yarn npm: 5.6.0 - /usr/local/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman SDKs: iOS SDK: Platforms: iOS 11.4, macOS 10.13, tvOS 11.4, watchOS 4.3 IDEs: Xcode: 9.4.1/9F2000 - /usr/bin/xcodebuild npmPackages: react: 16.4.1 => 16.4.1 react-native: 0.56.0 => 0.56.0 npmGlobalPackages: create-react-native-app: 1.0.0 react-native-cli: 2.0.1

Reproducible Demo

  1. react-native init
  2. react-native run-ios
  3. In Capabilities, enable both 'Notifications' and Background Modes -> Enable 'Remote notifications'
  4. Open Xcode and select a connected iPhone
  5. Launch/debug the app and open the Xcode console

A couple of notes:

  • Device is iPhone X on iOS 12.0 beta (16A5366a)
  • Building the app using Xcode 10.0 beta 2 (10L177m) beta, while react-native run-ios builds using Xcode 9.4.1
  • macOS is running 10.14 Beta (18A377a)
Bug DX iOS Locked PR Submitted Xcode

Most helpful comment

After a couple of hours of debugging, breakpoint hunting and diving into the React Native Libraries, I have found a solution that at least works for me.

TL; DR

Add the following line in your AppDelegate.m (you have to put it right below the line starting with jsCodeLocation = [[RCTBundleURLProvider sharedSettings] ...):

[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host];

The long version

The problem is a reconnecting WebSocket trying to access the Metro packager via http://localhost:8081/message?role=ios, which cannot be resolved, because localhostfrom the device's point of view would be itself, whereas the packager is still running on your MacBook. This is also the reason why this issue only occurs on actual devices and not when running the simulator on a MacBook. Therefore, the iPhone needs to access the package manager through your MacBook's URL in the local network.

The problem is located in line 63 of the init function of React Native's RCTPackagerConnection
class. It reads the value of the RCTBundleURLProvider's jsLocation property, which is never being set, hence it is empty. Now I don't know whether we are all missing some configuration part that would lead this to be set properly, but for me this is always empty. In the end, line 84 of RCTPackagerConnection falls back to localhostif no jsLocation was set.

Interestingly enough, there is a fancy mechanism to set the URL accordingly, implemented in RCTBundleURLProvider) and react-native/scripts/react-native-xcode.sh. The shell script is automatically executed as part of the Xcode build steps of every RN project. This mechanism will write your MacBook's IP address to a text file called ip.txt and allow RN on the device to read from it afterwards. By the way, the script also used to use xip.io as a workaround to the problem that the ATS (App Transport Security) doesn't allow non-HTTPS URLs, however xip.io has been removed from the code entirely a year ago. Unfortunately, React Native's official documentation has not been updated accordingly, adding to the frustration when trying to fix these kind of issues.

Now the weird part is that the mechanism to determine the IP address and passing it to the app on the device is only applied in the context of the first bootstrapping scripts in AppDelegate.m (inside the jsBundleURLForBundleRoot call):

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"CookingBuddyMobileApp"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

The WebSockets trying to (re-)connect to the packager afterwards don't know the IP and, as described above, fall back to localhost. Therefore, setting the RCTBundleURLProvider's jsLocation property in AppDelegate.m fixes the issue:

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host]; 

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"CookingBuddyMobileApp"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

This basically re-uses the existing jsCodeLocation property (which takes advantage of the fancy ip.txt mechanism mentioned above) and simply extracts the host (i.e. the IP address) from it (since jsCodeLocation is a full URL with scheme, path etc.) and sets the RCTBundleURLProvider's jsLocationproperty accordingly. This leads to all WebSockets to initialize correctly (i.e. not with localhostURLs, but with your MacBook's IP address.

I hope this helps! And if someone has a more "elegant solution", I would love to hear it.

@msand To me it seems as if this is a bug in RN, but I am not sure. Do you think it would be worth opening a new issue, or re-opening this one?

All 104 comments

UPDATE This only happens when I run it on an iOS 12 device!!! (Doesn't matter what I build with) Reverting back to iOS 11 for now.

same issue with 0.57.0 version:

react-native info
  React Native Environment Info:
    System:
      OS: macOS High Sierra 10.13.6
      CPU: x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz
      Memory: 690.77 MB / 16.00 GB
      Shell: 5.3 - /bin/zsh
    Binaries:
      Node: 8.11.4 - /usr/local/bin/node
      Yarn: 1.9.4 - /usr/local/bin/yarn
      npm: 5.6.0 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
    IDEs:
      Android Studio: 3.1 AI-173.4907809
      Xcode: 10.0/10A255 - /usr/bin/xcodebuild
    npmPackages:
      @types/react-native: ^0.56.21 => 0.56.21 
      react: 16.5.1 => 16.5.1 
      react-native: ^0.57.0 => 0.57.0 

Is this resolved? I'm also seeing messages like:
2018-09-18 15:25:36.721046-0700 AwesomeProject[18908:21074308] [] nw_socket_handle_socket_event [C4.1:1] Socket SO_ERROR [61: Connection refused]
2018-09-18 15:25:36.728264-0700 AwesomeProject[18908:21074308] [] nw_socket_handle_socket_event [C4.2:1] Socket SO_ERROR [61: Connection refused]
2018-09-18 15:25:36.734951-0700 AwesomeProject[18908:21074298] [] nw_connection_get_connected_socket [C4] Client called nw_connection_get_connected_socket on unconnected nw_connection

Temporary fix:

Edit Scheme => Run => Environment Variables => Add OS_ACTIVITY_MODE:disable

Temporary fix:

Edit Scheme => Run => Environment Variables => Add OS_ACTIVITY_MODE:disable

This works fine, but keep in mind that it also suppresses all NSLog output you may need for debugging.

I also have the same problem, it keeps running and the memory is getting big and big, when it reached 15G, my computer crushed

Any info on this? I am too seeing a spew of these errors in debug output when running my app on a device. I haven't tracked memory consumption on the device yet but I will do that soon to see if this is a show-stopping issue that would prevent me from releasing my app.

EDIT: While I haven't seen me any absurd memory growth, it is chewing through an abnormal amount of CPU while in this cycle of establishing connections.

Still broke :(

I also having same issue with xcode 10 and IOS12

Same issue on Xcode 10 and IOS12.

Same issue on Xcode 10 and IOS12.

Same with iOS 12.

I am receiving this error ReactProject[12849:185872] [] nw_connection_get_connected_socket [C62] Client called nw_connection_get_connected_socket on unconnected nw_connection and my computer becomes completely slow while running it.

+1

+1

The same problem for me on Xcode 10 iOS 12 Simulator.

Temporary fix:

Edit Scheme => Run => Environment Variables => Add OS_ACTIVITY_MODE:disable

This fixes the issue on iOS 12 Simulator. Could someone explain what this does?

I will test later on iOS 11.

I am facing the same issue as well.

same !

Hey all - “Same” and “+1” are not particularly helpful for this discussion.

Weird,

doing

rm -rf $TMPDIR/react-* && watchman watch-del-all && yarn cache clean

worked for me. Maybe it wouldn't hurt to add a --reset-cache after the start script, but I did not have to do that!

Same issue on Xcode 10 and IOS12

If someone is looking for temporary get rid of this issue then apply filter in XCode console with [info][tid:com.facebook.react.JavaScript]

So we can see our required debug log.. 😆

Also running into this.

please stop commenting with +1/"me too". It's more frustrating than helpful.

about this issue, it's caused by Apple changing the error messages in their network stack making our fishhook logic no longer work. (Found here: https://github.com/facebook/react-native/blob/master/Libraries/WebSocket/RCTReconnectingWebSocket.m)

@maicki do you have any spare cycles to take a look at getting this working?

No idea if this helps, but just an observation -- when I see this issue, I can watch the number of ports being reported for Xcode via Activity Monitor keeps climbing. On my Mac Pro trashcan, OSX will eventually become unusable and crash, usually when the ports climb to around 200,000.

Looks like the number of ports grows by about 20 every 2 seconds.

I don't see any odd data via netstat or lsof.

Hardly any CPU usage for me, just the ports slowly climbing and eventually OSX crashing and requiring a power cycle to recover.

xcode ports

Temporary fix:

Edit Scheme => Run => Environment Variables => Add OS_ACTIVITY_MODE:disable

This fix is devious, because even though it suppresses the warning, your computer will eventually crash.

When i run in Simulator or on Device, logs can be filtered using Console.app:

  1. Select your device (simulator or real device) on the left
  2. Right click on your application process and select "show process 'MyApp'"

Now you're only seeing output from your "MyApp" and you can start filtering out unwanted lines by right clicking them and selecting "Hide library 'theLibrary'".
To get clean logs i hide:

  • CFNetwork
  • libnetwork.dylib

It's a shame these filters cannot be saved, but at least console logging is now usable again.

Simplest way to turn off the Devtools connection in debug builds with embedded bundle file is, by adding these compiler flags into the Xcode project settings

ENABLE_PACKAGER_CONNECTION=0
RCT_ENABLE_INSPECTOR=0

Note: This completely disables debugging capability and will not even start the socket connection to the bundle location

I have a workaround available, requires patching the inspector and react-devtools. Check the two PRs that just referenced this issue.

If you don't want to wait for a new release to fix this, you can use patch-package and this for rn: react-native+0.57.5.patch

patch-package
--- a/node_modules/react-native/React/Inspector/RCTInspectorPackagerConnection.m
+++ b/node_modules/react-native/React/Inspector/RCTInspectorPackagerConnection.m
@@ -196,7 +196,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init)
     [self abort:@"Websocket exception"
       withCause:error];
   }
-  if (!_closed) {
+  if (!_closed && [error code] != ECONNREFUSED) {
     [self reconnect];
   }
 }

and react-devtools: react-devtools-core+3.4.3.patch

patch-package
--- a/node_modules/react-devtools-core/build/backend.js
+++ b/node_modules/react-devtools-core/build/backend.js
@@ -23,11 +23,16 @@
                     return connectToDevTools(options);
                 }, 2e3);
             }
-            function handleClose() {
-                hasClosed || (hasClosed = !0, scheduleRetry(), closeListeners.forEach(function(fn) {
-                    return fn();
-                }));
-            }
+          function handleClose() {
+            hasClosed || (hasClosed = !0, scheduleRetry(), closeListeners.forEach(function(fn) {
+              return fn();
+            }));
+          }
+          function handleError(err) {
+            hasClosed || (hasClosed = !0, closeListeners.forEach(function(fn) {
+              return fn();
+            }));
+          }
             function handleMessage(evt) {
                 var data;
                 try {
@@ -48,7 +53,7 @@
             } : _ref$isAppActive;
             if (!isAppActive()) return void scheduleRetry();
             var messageListeners = [], closeListeners = [], uri = "ws://" + host + ":" + port, ws = websocket ? websocket : new window.WebSocket(uri);
-            ws.onclose = handleClose, ws.onerror = handleClose, ws.onmessage = handleMessage, 
+            ws.onclose = handleClose, ws.onerror = handleError, ws.onmessage = handleMessage,
             ws.onopen = function() {
                 var wall = {
                     listen: function(fn) {

patch-package
--- a/node_modules/react-native/React/Inspector/RCTInspectorPackagerConnection.m
+++ b/node_modules/react-native/React/Inspector/RCTInspectorPackagerConnection.m
@@ -196,7 +196,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init)
[self abort:@"Websocket exception"
withCause:error];
}
- if (!_closed) {
+ if (!_closed && [error code] != ECONNREFUSED) {
[self reconnect];
}
}

Thank you @msand, you're saver!

I think those "+1" and "same here" were helpful after all. The problem here was not "how to fix it". Everything actually was working, it's just some React Native optional internals & tools were broken. Developers absolutely can live without them. And there were no info about how to just opt out dev tools and it's auto-reconnect.

Seriously. Why do we need to fix auto-reconnect logic for dev-tools? We may just disable dev-tools and work happily.

Patch did it's work perfectly! But also we could solve that much easier by just disabling auto-reconnect at all and save tons of nerves many months ago. And yes, it wasn't clear at all where these log lines come from and how to disable dev-tools auto-reconnect.

It's sometimes amazing how React Native is trying to force us to use something that we developers actually don't need and something that makes experience even worse.

In my Log I am also facing the same issue. Also Command + r not refreshing the simulator

If you don't want to wait for a new release to fix this, you can use patch-package and this for rn: react-native+0.57.5.patch

patch-package
--- a/node_modules/react-native/React/Inspector/RCTInspectorPackagerConnection.m
+++ b/node_modules/react-native/React/Inspector/RCTInspectorPackagerConnection.m
@@ -196,7 +196,7 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init)
     [self abort:@"Websocket exception"
       withCause:error];
   }
-  if (!_closed) {
+  if (!_closed && [error code] != ECONNREFUSED) {
     [self reconnect];
   }
 }

and react-devtools: react-devtools-core+3.4.3.patch

patch-package
--- a/node_modules/react-devtools-core/build/backend.js
+++ b/node_modules/react-devtools-core/build/backend.js
@@ -23,11 +23,16 @@
                     return connectToDevTools(options);
                 }, 2e3);
             }
-            function handleClose() {
-                hasClosed || (hasClosed = !0, scheduleRetry(), closeListeners.forEach(function(fn) {
-                    return fn();
-                }));
-            }
+          function handleClose() {
+            hasClosed || (hasClosed = !0, scheduleRetry(), closeListeners.forEach(function(fn) {
+              return fn();
+            }));
+          }
+          function handleError(err) {
+            hasClosed || (hasClosed = !0, closeListeners.forEach(function(fn) {
+              return fn();
+            }));
+          }
             function handleMessage(evt) {
                 var data;
                 try {
@@ -48,7 +53,7 @@
             } : _ref$isAppActive;
             if (!isAppActive()) return void scheduleRetry();
             var messageListeners = [], closeListeners = [], uri = "ws://" + host + ":" + port, ws = websocket ? websocket : new window.WebSocket(uri);
-            ws.onclose = handleClose, ws.onerror = handleClose, ws.onmessage = handleMessage, 
+            ws.onclose = handleClose, ws.onerror = handleError, ws.onmessage = handleMessage,
             ws.onopen = function() {
                 var wall = {
                     listen: function(fn) {

@msand how do I apply this patch?

@riobijanero check the documentation of patch-package https://github.com/ds300/patch-package/blob/master/README.md#set-up

In short, save those two patches as two files in a folder called patches in your project root (same as where your package.json lives) add patch-package as a dev dependency, and add it as a postinstall script to be run on each yarn/npm install

Btw, I mostly made these patches to point out that there's significant value in changing the logic in at least these two places to something else, but the change I made isn't anywhere near the best logic for handling these errors in general. Ideally it would treat different types of errors differently, and warn if e.g. the devtools / inspector ports aren't open, and, at least if the connection attempt fails some number of times without a single successful attempt, it would stop trying. The option not to even attempt connecting would also be a nice option to have easily available/documented.

please stop commenting with +1/"me too". It's more frustrating than helpful.

about this issue, it's caused by Apple changing the error messages in their network stack making our fishhook logic no longer work. (Found here: https://github.com/facebook/react-native/blob/master/Libraries/WebSocket/RCTReconnectingWebSocket.m)

@maicki do you have any spare cycles to take a look at getting this working?

stop Remote JS Debugging fix this issue .

I would much rather fix the logging issue than disable RCTReconnectingWebSocket. Right now it's used to let people connect the packager at any time instead of only looking for it on startup.

If we were to remove it, I'm sure we'd get questions from people asking why their app isn't connecting to the packager

update 0.57.0 to 0.57.8, i have same issue.

react-native info:

  React Native Environment Info:
    System:
      OS: macOS High Sierra 10.13.6
      CPU: x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
      Memory: 88.89 MB / 16.00 GB
      Shell: 5.6.2 - /usr/local/bin/zsh
    Binaries:
      Node: 10.15.0 - ~/.node/v10.15.0/bin/node
      Yarn: 1.13.0 - ~/.node/v10.15.0/bin/yarn
      npm: 6.5.0 - ~/.node/v10.15.0/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.1, macOS 10.14, tvOS 12.1, watchOS 5.1
      Android SDK:
        Build Tools: 20.0.0, 21.1.2, 22.0.1, 23.0.1, 23.0.3, 24.0.3, 25.0.0, 25.0.3, 26.0.2, 26.0.3, 27.0.3, 28.0.3
        API Levels: 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28
    IDEs:
      Android Studio: 3.2 AI-181.5540.7.32.5056338
      Xcode: 10.1/10B61 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.7.0 => 16.7.0
      react-native: 0.57.8 => 0.57.8
    npmGlobalPackages:
      react-native-cli: 2.0.1

@riobijanero your patch worked wonderfully with [email protected], but [email protected] is minified, so unfortunately the patch is no longer functional.

@rickhanlonii This is the issue I mentioned on Twitter. I think this has been a historical dev-ex issue in RN. What I've heard is that RN is set up to try to connect to react-devtools because that's how FB works internally. But a lot of us using the open source build don't use react-devtools, so we get a lot of connection error spam looking at the logs. A solution might be for RN to give up trying to connect to devtools after 10 seconds or so.

A related issue is that react-native log-ios hasn't worked for a while (cc @nparashuram) . I think xcode moved the logs at some point, and so you can't easily look at the ios console.logs without opening xcode, knowing the magical log command log stream --predicate '(processImagePath contains \"AppName\") and senderImageUUID == processImageUUID', or using a tool like reactotron.

If we could get react-native log-ios to work well without having to open xcode and without getting a lot of connection errors it'd make the developer experience 💯

@mmmulani Logging garbage is not coming from packager connection errors. I got packager running all the time and it's working as expected but I still can see a huge bunch of such logs. BTW on device there's twice much of them vs simulator.

oh interesting, could you set a breakpoint in RCTReconnectingWebSocket and see what’s creating it then?

@mmccartney Can't get breakpoint event triggered in RCTReconnectingWebSocket but I get it in RCTInspectorPackagerConnection.m @ method:

// analogous to InspectorPackagerConnection.Connection.onFailure(...)
- (void)webSocket:(RCTSRWebSocket *)webSocket didFailWithError:(NSError *)error
{
  if (_webSocket) {
    [self abort:@"Websocket exception"
      withCause:error]; // ! breakpoint is activated here
  }
  if (!_closed) {
    [self reconnect]; // ! breakpoint is activated here
  }
}

I do not use remote js debugging and haxe those logs generated every 2 or 3 seconds. Where does it come from exactly?

This is coming from React native trying to connect to react-devtools, not
the packaging server

On Fri, Jan 25, 2019, 09:14 Thomas Fétiveau <[email protected] wrote:

I do not use remote js debugging and haxe those logs generated every 2 or
3 seconds. Where does it come from exactly?


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/facebook/react-native/issues/21030#issuecomment-457584735,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAeDc5mSD-BX0d4GyvR-o3QSq0_MNqtUks5vGxFKgaJpZM4WglZ1
.

trying to connect to react-devtools, not the packaging server

@dslounge you mean trying to connect to react-devtools instead of the packaging server?

I don't understand how did this happen, I did not have this error few days ago and I haven't changed anything to my config nor dependencies versions...

I think it's been a constant issue for about a year or longer. Try turning
on react-devtools and you'll see it go away.

On Fri, Jan 25, 2019, 11:34 Thomas Fétiveau <[email protected] wrote:

trying to connect to react-devtools, not the packaging server

@dslounge https://github.com/dslounge you mean trying to connect to
react-devtools instead of the packaging server?

I don't understand how did this happen, I did not have this error few days
ago and I haven't changed anything to my config nor dependencies versions...


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/facebook/react-native/issues/21030#issuecomment-457632345,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAeDczh_SAdJ-562jAAz1MTf_aGDRSCBks5vGzIngaJpZM4WglZ1
.

@msand Thanks for putting together those PRs! Do you have any updates or knowledge about when / if they'll be merged?

It's still an issue on 0.58.3 :)

If you're using react-native-macos, this solution will help you:

https://medium.com/@mimicatcodes/how-to-get-rid-of-unwanted-logs-in-the-console-xcode-8-6c1909ed75d8

Side note: NSLog calls won't be visible, so be sure to use RCTLog instead. (when using Objective-C)

@aleclarson thanks for the workaround.

Again, "+1" or "me too" comments are not helpful.

I'm using XCode for watching logs. This is very convinient. Faster and deeper in any case than debugging via browser based remote debugger or via react dev tools. Why react native team totally ignores this issue is extremely strange to me and even make me think of switching to another platform.

Yes, I prefer to use native platform tools. For MacOS and iOS development this is XCode. We don't need more than that. OK, we also must use some editor for JavaScript and auto-started NodeJS based packager. But please, don't force extras, that's already too much!

so no ones cares about this isssue!?it has been a long time for opened here!!it's very affecting the progress of work

Upgraded to 0.58.5 and the issue still exists.

For those who don't understand why this is so annoying: Our app use Cocoapods to integrate React Native and is developed by React Native developers and native developers at the same time. As seen from native developers, we don't install React Dev Tools so the app could never get connected to a dev tool, which leads the infinite trolling of the nw_socket_handle_socket_event log every second, making the Xcode console totally unusable.

For those who have been annoyed like me:
Since facebook never wants to solve this issue, I figured out a way to make it stop. The credit goes to @anilmanukonda . If you are like me using Cocoapods to integrate React, and don't use React Dev Tools, add the code below to your podfile, then in Xcode Clean Build Folder, rebuild.

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      if target.name == 'React' and config.name == 'Debug' then
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = ['$(inherited)', 'RCTLOG_ENABLED=0', 'ENABLE_PACKAGER_CONNECTION=0', 'RCT_ENABLE_INSPECTOR=0']
      end
    end
  end
end

@xiao99xiao it seems the bot closed it because someone merged a PR yesterday that's supposed to fix it. Do you think that'll resolve your particular situation?

@noahtallen Thanks for clarifying. Seems it should resolve the issue in my case, however I can't verify it until next React Native release and my React Native developer collegue updates our project. I should leave the question to others here :)

Seems we still need to wait for https://github.com/facebook/react-devtools/pull/1248 to fix this issue

@sunnylqm I made a build of my patch (cherry picked it on top of v3.4.2 first, which is the version used/locked in the 0.58-stable branch of react-native) and published it to github: https://github.com/msand/react-devtools-core
You can try it using e.g.
yarn add react-devtools-core@msand/react-devtools-core#4c30959

Also cherry picked the patch on top of the 3.6.0 release (which is the one used in 0.59-stable), in case you want the latest version and hooks support etc.
yarn add react-devtools-core@msand/react-devtools-core#4880490

At least the 0.59-stable branch contains my patch for react-native, and is available starting from 0.59.0-rc.3 which was released three days ago.

So, if you run:

react-native init --version 0.59.0-rc.3 MyNewApp
cd MyNewApp
yarn add react-devtools-core@msand/react-devtools-core#4880490
react-native run-ios

Then you should be free from errors.

Actually the patch seems to be available in the 0.58-stable branch as well, starting with 0.58.6 which was released two days ago.
So, running:

react-native-git-upgrade

or

yarn add react-native

(and adjusting the react version etc.)

And then:

yarn add react-devtools-core@msand/react-devtools-core#4c30959
react-native run-ios

Should work as well. The same applies for react-native init without specifying a version (until 0.59 is released).

Actually the patch seems to be available in the 0.58-stable branch as well, starting with 0.58.6 which was released two days ago.
So, running:

react-native-git-upgrade

or

yarn add react-native

(and adjusting the react version etc.)

And then:

yarn add react-devtools-core@msand/react-devtools-core#4c30959
react-native run-ios

Should work as well. The same applies for react-native init without specifying a version (until 0.59 is released).

Thanks it solved issue!

yarn add react-native
yarn add react-devtools-core@msand/react-devtools-core#4c30959

@msand First of all, thanks for taking care of this!

I am also having this issue, however I still have not managed to solve it. My Xcode logs are piling up with nw_socket_handle_socket_event [C581.2:1] Socket SO_ERROR [61: Connection refused] entries, the number of Xcode's ports in the activity monitor increase by ~20 per second, as described above. In addition to that, any XHR requests I make from my app seem to display a failure with a huge delay (like 1-2 minutes), is it possible that they are blocked/queued?

It is important to mention that all of this only happens when testing with a real device (iPhone XS, iOS 12.1.4). With a simulated iPhone XS, iOS 12.1, I don't get any of these errors.

I upgraded to RN 0.58.6 via react-native-git-upgrade as described in the React Native documentation successfully and executed npm install react-devtools-core@msand/react-devtools-core#4c30959 --save (instead of yarn add react-devtools-core@msand/react-devtools-core#4c30959, hope that was correct).

Am I missing something?

This is quite frustrating, since it not only clogs the log view, but also seems to block my XHR requests. But since I am new to RN, maybe it's me! :) Thanks in advance.

Still, I have same issues with latest version

Try yarn upgrade react-native(if your rn version already >=0.58.6) to upgrade react-devltools-core to the latest version 3.6.1, which includes the patch.

If you're still having issues, can you make a reproducible demo? Preferably with a fresh empty project with nothing else: react-native init MyNewApp

If you're still having issues, can you make a reproducible demo? Preferably with a fresh empty project with nothing else: react-native init MyNewApp

Unfortunately, I still can't get it to work, even with a freshly set up project. I created a repo with the code and a readme, including a screenshot - if there is any other info that can help figuring out the issue, please let me know. Thanks!

https://github.com/dembe1/rn-connection-issue

Ah, you're using a real device no? I guess you have some firewall issues or need to open some ports. I don't have access to any iPhone so I can't really help you with that.

So, if you run:

react-native init --version 0.59.0-rc.3 MyNewApp
cd MyNewApp
yarn add react-devtools-core@msand/react-devtools-core#4880490
react-native run-ios

Then you should be free from errors.

Thanks for working on this @msand!

I just inited a clean 0.59.0-rc.3 app and this is still happening for me :\

  • iPhone X (Device, not simulator)
  • iOS 12.1.4

Thanks @msand, does react-native version matter? I upgraded react-devtools-core to 3.6.1 in my project that uses react-native v0.58.1. But the issue does not solved.

demo here: https://github.com/zfanta/demo

@zfanta Yes, rn version must be >= 0.58.6

Have you done this? https://facebook.github.io/react-native/docs/running-on-device#2-ip-address

Hey @msand , I tried this and it doesn't help. I'm still seeing my Xcode logs spammed by this socket message. I'm on RN 0.58.6.

Hi @msand, I tried adding yarn add react-devtools-core@msand/react-devtools-core#4c30959 to my 0.58.6 RN project and then stopped metro and did a clean build and run in Xcode but that didn't help. I am still seeing Xcode's log spammed with the following every 2 seconds:

019-03-08 16:07:53.483125-0800 BidVidClientMobile[40953:7799138] TCP Conn 0x280fcc300 Failed : error 0:61 [61]
2019-03-08 16:07:55.496783-0800 BidVidClientMobile[40953:7799138] [] nw_socket_handle_socket_event [C33.1:1] Socket SO_ERROR [61: Connection refused]
2019-03-08 16:07:55.499286-0800 BidVidClientMobile[40953:7799138] [] nw_socket_handle_socket_event [C33.2:1] Socket SO_ERROR [61: Connection refused]
2019-03-08 16:07:55.500128-0800 BidVidClientMobile[40953:7799132] [] nw_connection_get_connected_socket [C33] Client called nw_connection_get_connected_socket on unconnected nw_connection

Also the number of open ports in Xcode as visible in Activity Monitor is going up and up without limit. I am running on an actual iPhone on iOS 12.

Any ideas? It appears that the patch does NOT fix the issue and this is really making it difficult to do any Xcode logging (and the ports may be exhausted at some point) ...

Or did I need to do something else after installing the devltools patch?

Thanks for all of your help with this!

I haven't had any iPhone since I started doing react-native things. So I've never had a real iPhone connected to Xcode yet, and can't really help you with that. Do you have the debugger and inspector working? Otherwise, perhaps someone else who has that working in this thread can help you. I would suspect the debugger doesn't work either in case you're still getting errors.

After a couple of hours of debugging, breakpoint hunting and diving into the React Native Libraries, I have found a solution that at least works for me.

TL; DR

Add the following line in your AppDelegate.m (you have to put it right below the line starting with jsCodeLocation = [[RCTBundleURLProvider sharedSettings] ...):

[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host];

The long version

The problem is a reconnecting WebSocket trying to access the Metro packager via http://localhost:8081/message?role=ios, which cannot be resolved, because localhostfrom the device's point of view would be itself, whereas the packager is still running on your MacBook. This is also the reason why this issue only occurs on actual devices and not when running the simulator on a MacBook. Therefore, the iPhone needs to access the package manager through your MacBook's URL in the local network.

The problem is located in line 63 of the init function of React Native's RCTPackagerConnection
class. It reads the value of the RCTBundleURLProvider's jsLocation property, which is never being set, hence it is empty. Now I don't know whether we are all missing some configuration part that would lead this to be set properly, but for me this is always empty. In the end, line 84 of RCTPackagerConnection falls back to localhostif no jsLocation was set.

Interestingly enough, there is a fancy mechanism to set the URL accordingly, implemented in RCTBundleURLProvider) and react-native/scripts/react-native-xcode.sh. The shell script is automatically executed as part of the Xcode build steps of every RN project. This mechanism will write your MacBook's IP address to a text file called ip.txt and allow RN on the device to read from it afterwards. By the way, the script also used to use xip.io as a workaround to the problem that the ATS (App Transport Security) doesn't allow non-HTTPS URLs, however xip.io has been removed from the code entirely a year ago. Unfortunately, React Native's official documentation has not been updated accordingly, adding to the frustration when trying to fix these kind of issues.

Now the weird part is that the mechanism to determine the IP address and passing it to the app on the device is only applied in the context of the first bootstrapping scripts in AppDelegate.m (inside the jsBundleURLForBundleRoot call):

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"CookingBuddyMobileApp"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

The WebSockets trying to (re-)connect to the packager afterwards don't know the IP and, as described above, fall back to localhost. Therefore, setting the RCTBundleURLProvider's jsLocation property in AppDelegate.m fixes the issue:

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host]; 

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"CookingBuddyMobileApp"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

This basically re-uses the existing jsCodeLocation property (which takes advantage of the fancy ip.txt mechanism mentioned above) and simply extracts the host (i.e. the IP address) from it (since jsCodeLocation is a full URL with scheme, path etc.) and sets the RCTBundleURLProvider's jsLocationproperty accordingly. This leads to all WebSockets to initialize correctly (i.e. not with localhostURLs, but with your MacBook's IP address.

I hope this helps! And if someone has a more "elegant solution", I would love to hear it.

@msand To me it seems as if this is a bug in RN, but I am not sure. Do you think it would be worth opening a new issue, or re-opening this one?

@dembe1 Excellent work! It probably makes sense to open a new issue, and make a new pull request referencing that. It'll probably get more attention from the maintainers that way as this issue is already closed. Can of course reference this issue from the new one, that'll give good context for any maintainers to evaluate the nature of the bug and fix.

After a couple of hours of debugging, breakpoint hunting and diving into the React Native Libraries, I have found a solution that at least works for me.

TL; DR

Add the following line in your AppDelegate.m (you have to put it right below the line starting with jsCodeLocation = [[RCTBundleURLProvider sharedSettings] ...):

[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host];

The long version

The problem is a reconnecting WebSocket trying to access the Metro packager via http://localhost:8081/message?role=ios, which cannot be resolved, because localhostfrom the device's point of view would be itself, whereas the packager is still running on your MacBook. This is also the reason why this issue only occurs on actual devices and not when running the simulator on a MacBook. Therefore, the iPhone needs to access the package manager through your MacBook's URL in the local network.

The problem is located in line 63 of the init function of React Native's RCTPackagerConnection class. It reads the value of the RCTBundleURLProvider's jsLocation property, which is never being set, hence it is empty. Now I don't know whether we are all missing some configuration part that would lead this to be set properly, but for me this is always empty. In the end, line 84 of RCTPackagerConnection falls back to localhostif no jsLocation was set.

Interestingly enough, there is a fancy mechanism to set the URL accordingly, implemented in RCTBundleURLProvider) and react-native/scripts/react-native-xcode.sh. The shell script is automatically executed as part of the Xcode build steps of every RN project. This mechanism will write your MacBook's IP address to a text file called ip.txt and allow RN on the device to read from it afterwards. By the way, the script also used to use xip.io as a workaround to the problem that the ATS (App Transport Security) doesn't allow non-HTTPS URLs, however xip.io has been removed from the code entirely a year ago. Unfortunately, React Native's official documentation has not been updated accordingly, adding to the frustration when trying to fix these kind of issues.

Now the weird part is that the mechanism to determine the IP address and passing it to the app on the device is only applied in the context of the first bootstrapping scripts in AppDelegate.m (inside the jsBundleURLForBundleRoot call):

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"CookingBuddyMobileApp"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

The WebSockets trying to (re-)connect to the packager afterwards don't know the IP and, as described above, fall back to localhost. Therefore, setting the RCTBundleURLProvider's jsLocation property in AppDelegate.m fixes the issue:

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host]; 

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"CookingBuddyMobileApp"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

This basically re-uses the existing jsCodeLocation property (which takes advantage of the fancy ip.txt mechanism mentioned above) and simply extracts the host (i.e. the IP address) from it (since jsCodeLocation is a full URL with scheme, path etc.) and sets the RCTBundleURLProvider's jsLocationproperty accordingly. This leads to all WebSockets to initialize correctly (i.e. not with localhostURLs, but with your MacBook's IP address.

I hope this helps! And if someone has a more "elegant solution", I would love to hear it.

@msand To me it seems as if this is a bug in RN, but I am not sure. Do you think it would be worth opening a new issue, or re-opening this one?

Don't work on my project, same issue again

[3927:38003] [] nw_socket_handle_socket_event [C17.1:1] Socket SO_ERROR [61: Connection refused] a lot of times!

After a couple of hours of debugging, breakpoint hunting and diving into the React Native Libraries, I have found a solution that at least works for me.

TL; DR

Add the following line in your AppDelegate.m (you have to put it right below the line starting with jsCodeLocation = [[RCTBundleURLProvider sharedSettings] ...):

[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host];

The long version

The problem is a reconnecting WebSocket trying to access the Metro packager via http://localhost:8081/message?role=ios, which cannot be resolved, because localhostfrom the device's point of view would be itself, whereas the packager is still running on your MacBook. This is also the reason why this issue only occurs on actual devices and not when running the simulator on a MacBook. Therefore, the iPhone needs to access the package manager through your MacBook's URL in the local network.

The problem is located in line 63 of the init function of React Native's RCTPackagerConnection class. It reads the value of the RCTBundleURLProvider's jsLocation property, which is never being set, hence it is empty. Now I don't know whether we are all missing some configuration part that would lead this to be set properly, but for me this is always empty. In the end, line 84 of RCTPackagerConnection falls back to localhostif no jsLocation was set.

Interestingly enough, there is a fancy mechanism to set the URL accordingly, implemented in RCTBundleURLProvider) and react-native/scripts/react-native-xcode.sh. The shell script is automatically executed as part of the Xcode build steps of every RN project. This mechanism will write your MacBook's IP address to a text file called ip.txt and allow RN on the device to read from it afterwards. By the way, the script also used to use xip.io as a workaround to the problem that the ATS (App Transport Security) doesn't allow non-HTTPS URLs, however xip.io has been removed from the code entirely a year ago. Unfortunately, React Native's official documentation has not been updated accordingly, adding to the frustration when trying to fix these kind of issues.

Now the weird part is that the mechanism to determine the IP address and passing it to the app on the device is only applied in the context of the first bootstrapping scripts in AppDelegate.m (inside the jsBundleURLForBundleRoot call):

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"CookingBuddyMobileApp"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

The WebSockets trying to (re-)connect to the packager afterwards don't know the IP and, as described above, fall back to localhost. Therefore, setting the RCTBundleURLProvider's jsLocation property in AppDelegate.m fixes the issue:

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host]; 

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                             moduleName:@"CookingBuddyMobileApp"
                                             initialProperties:nil
                                             launchOptions:launchOptions];

This basically re-uses the existing jsCodeLocation property (which takes advantage of the fancy ip.txt mechanism mentioned above) and simply extracts the host (i.e. the IP address) from it (since jsCodeLocation is a full URL with scheme, path etc.) and sets the RCTBundleURLProvider's jsLocationproperty accordingly. This leads to all WebSockets to initialize correctly (i.e. not with localhostURLs, but with your MacBook's IP address.

I hope this helps! And if someone has a more "elegant solution", I would love to hear it.

@msand To me it seems as if this is a bug in RN, but I am not sure. Do you think it would be worth opening a new issue, or re-opening this one?

It worked for after I spent so many hours to find a fix.
I am using......
react-native: 0.52.0
OSX: 10.14.3
Xcode: 10.1
iOS: 12.1.4

I haven't faced this issue in react-native version is 0.58.4 as the changes in react-native-xcode.sh mentioned in this solution, is already there.

If you use an Expo bare app then you need to implement the solution of @deadwater88 in https://github.com/facebook/react-native/commit/7fce997ea5bd446b1410b347a02f21540c924d06 since the jsCodeLocation mentioned by @rajeshde is not in your AppDelegate.

For me, @dembe1's solution didn't work since I'm using Electrode Native and we don't have that in our AppDelegate.m. However, we don't use sockets in our react-native app so I went to the source of the reconnections and prevented them from happening.

On RN 0.57.8 and electrode-native version 0.30, the culprit was RCTInspectorPackagerConnection.m at line 200.

- (void)webSocket:(RCTSRWebSocket *)webSocket didFailWithError:(NSError *)error
{
  if (_webSocket) {
    [self abort:@"Websocket exception"
      withCause:error];
  }
  if (!_closed) {
    [self closeAllConnections]; // <- Change to this. Before it was `[self reconnect];
  }
}

This removed all those annoying reconnect logs.

This change is a bit overkill, I'm sure commenting out the [self reconnect]; would have been enough, but since we don't use sockets, this is fine for us. It might have some side-effects, I'm no iOS expert, but it works for me, so maybe it will work for others.

UPDATE:

For my team members, that wasn't enough. I also had to remove the [self reconnect]; calls on RCTReconnectingWebSocket.m on lines 166 and 172.

After that, no more logs.

I'm using react native 0.59.5 and I'm getting these errors. However this version of react native uses:
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
instead of RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
so I can't implement the:
[[RCTBundleURLProvider sharedSettings] setJsLocation:jsCodeLocation.host]; fix.
Is there any way to implement that fix using the bridge instead of initWithBundle?

Having the same issue on iOS 12.1.4, react-native: 0.59.5, XCode 10.2.1.

Runs many times:

2019-05-15 16:21:41.751022+0900 AppName[525:278667] TCP Conn 0x2820d4480 Failed : error 0:61 [61]
2019-05-15 16:21:43.869817+0900 AppName[525:252581] [] nw_socket_handle_socket_event [C25.1:1] Socket SO_ERROR [61: Connection refused]

Any updates?

Was having the same issue on:

  • IOS 12.2
  • XCode 12.2.1

  • RN 0.59.8

Looking at the comments on a number of posts I was able to resolve the issue by applying pretty much the same fix to AppDelegate.m. First of all, I'm terribly new to Objective-C so I'm sure this could be prettier, but its effective:

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  NSURL *jsUrl = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
  [[RCTBundleURLProvider sharedSettings] setJsLocation:jsUrl.host];
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@kenjdavidson thanks, it works perfectly! Just you can optimize the code a little bit by reusing the jsUrl variable:

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  NSURL *jsUrl = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
  [[RCTBundleURLProvider sharedSettings] setJsLocation:jsUrl.host];
  return jsUrl;
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

https://github.com/facebook/react-native/issues/24023#issuecomment-474608280 @patrickkempff 's solution possibly help

I'm also on 0.59.8 and the latest iOS and Xcode. My workaround looks like this:

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  NSURL *jsUrl = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
  [[RCTBundleURLProvider sharedSettings] setJsLocation:jsUrl.host];
  return jsUrl;
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

The errors are gone while I _do_ have a JS debugger open, but

2019-05-26 13:10:24.616366-0400 zonder[73455:1923229] [] nw_socket_handle_socket_event [C224.1:1] Socket SO_ERROR [61: Connection refused]
2019-05-26 13:10:24.618005-0400 zonder[73455:1923229] [] nw_socket_handle_socket_event [C224.2:1] Socket SO_ERROR [61: Connection refused]
2019-05-26 13:10:24.618761-0400 zonder[73455:1923229] [] nw_connection_get_connected_socket [C224] Client called nw_connection_get_connected_socket on unconnected nw_connection

just repeats indefinitely while I'm not debugging JS. So I guess the solution isn't working for me :(

@noahtallen, @IAmMarcellus I’ve found moving the RCTBundleURLProvider call to applicationDidFinishLaunchingWithOptions seems to fix the nw_socket_handle_socket_event errors both in and not in JS debug mode.

[[RCTBundleURLProvider sharedSettings] setJsLocation:[self sourceURLForBridge:bridge].host];

I added the line directly after the [[RCTRootView alloc] initWithBridge:bridge... call.

@dshepherd Huh. I just tried that and the logs still show up for me

Did all of the above, but did not really work. Then I noticed a CORS error in the Chrome debugger. Switched to React Native Debugger (https://github.com/jhen0409/react-native-debugger), rebuild the app, and it started working on my device.

The cors error prevented from connecting to the socket i guess

I hope this could be helpful to someone.

To summarize what I did:

  1. Editted my AppDelegate.m to reflect the latest template version, as I was using a version that looked a bit different. Latest version: https://github.com/facebook/react-native/blob/master/template/ios/HelloWorld/AppDelegate.m
  2. Then, editted my AppDelegate.m to use the change suggested above: https://github.com/facebook/react-native/issues/21030#issuecomment-493392051
  3. Close any open Chrome debugger
  4. Open the React Native Debugger
  5. Clean build
  6. Rebuild the App, target your own device
  7. Wait for the Metro bundler to complete bundling (see your terminal), that could take a little. In the mean time you'll see websocket connection errors, as the bundler is not ready yet.
  8. Wait for the app to open. Logs should now start flowing into React Native Debugger

While the app is running, you should not see any socket connection errors again in the logs

AppDelegate.m

/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#import "AppDelegate.h"
#import <AppCenterReactNativeCrashes/AppCenterReactNativeCrashes.h>
#import <AppCenterReactNativeAnalytics/AppCenterReactNativeAnalytics.h>
#import <AppCenterReactNative/AppCenterReactNative.h>

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNSplashScreen.h"

// iOS 9.x or newer
// https://facebook.github.io/react-native/docs/linking
#import <React/RCTLinkingManager.h>

@implementation AppDelegate

// https://facebook.github.io/react-native/docs/linking
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [RCTLinkingManager application:application openURL:url options:options];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

  // Custom added
  [AppCenterReactNativeCrashes registerWithAutomaticProcessing];
  [AppCenterReactNativeAnalytics registerWithInitiallyEnabled:false];
  [AppCenterReactNative register];

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"MyApp"
                                            initialProperties:nil];

  // Custom editted
  // Original:
  // rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  rootView.backgroundColor = [UIColor blackColor];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  // Custom added
  [RNSplashScreen show];

  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG

  // Custom added:
  // This prevents the logs from constantly showing websocket connection errors
  // https://github.com/facebook/react-native/issues/21030#issuecomment-493392051
  // original:
  // return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
  NSURL *jsUrl = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
  [[RCTBundleURLProvider sharedSettings] setJsLocation:jsUrl.host];
  return jsUrl;
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end


I'm also using react native debugger (which works great like you say!), but the logs show up for me when I turn off remote JS debugging

@dembe1 solution from Mar 10 worked for me. He gives an excellent explanation of this issue btw!

The same problem is still present even on 0.59.9, I wonder how facebook engineers don't run in the same issue on daily basis 🤔

Okay on 0.59.9 cleaning up the build folder and rebuilding the app helps. If you need a debuger, https://github.com/jhen0409/react-native-debugger works as @jvandenaardweg suggested (chrome debugger shows CORB errors).

The annoying thing is that even with the app working and debugger working I see a neverending stream of errors in xcode console:

2019-08-12 12:37:12.707914+0100 MyApp[13292:3989531] [] nw_socket_handle_socket_event [C15913.1:1] Socket SO_ERROR [61: Connection refused]
2019-08-12 12:37:12.708742+0100 MyApp[13292:3989531] [] nw_socket_handle_socket_event [C15913.2:1] Socket SO_ERROR [61: Connection refused]
2019-08-12 12:37:12.708899+0100 MyApp[13292:3989451] [] nw_connection_get_connected_socket [C15913] Client called nw_connection_get_connected_socket on unconnected nw_connection
2019-08-12 12:37:12.708912+0100 MyApp[13292:3989451] TCP Conn 0x28085ad00 Failed : error 0:61 [61]

I mean, what exactly is it trying to connect to? The Metro bundler works properly and the debugger is connected, what's happening?

I think fb uses quite a different debug setup internally, and it's supposed to connect to that.

Kinda ridiculous, that everyone is struggling with the tools rather than the actual appplication code.

Xcode 11, IOS13, RN 0.57.8
stuck here.

2019-09-30 17:59:34.364815+0800 kardashian[8997:267918] [] nw_socket_handle_socket_event [C268.2:1] Socket SO_ERROR [61: Connection refused]
2019-09-30 17:59:34.365713+0800 kardashian[8997:267914] [] nw_connection_get_connected_socket [C268] Client called nw_connection_get_connected_socket on unconnected nw_connection
2019-09-30 17:59:36.379120+0800 kardashian[8997:267918] [] nw_socket_handle_socket_event [C269.1:1] Socket SO_ERROR [61: Connection refused]
2019-09-30 17:59:36.380715+0800 kardashian[8997:267918] [] nw_socket_handle_socket_event [C269.2:1] Socket SO_ERROR [61: Connection refused]
2019-09-30 17:59:36.381649+0800 kardashian[8997:267907] [] nw_connection_get_connected_socket [C269] Client called nw_connection_get_connected_socket on unconnected nw_connection
2019-09-30 17:59:38.395820+0800 kardashian[8997:267907] [] nw_socket_handle_socket_event [C270.1:1] Socket SO_ERROR [61: Connection refused]
2019-09-30 17:59:38.397339+0800 kardashian[8997:267907] [] nw_socket_handle_socket_event [C270.2:1] Socket SO_ERROR [61: Connection refused]

Possible solution: Check if your mac and phone are on the same wifi network lol :((.

Possible solution: Check if your mac and phone are on the same wifi network lol :((.

of cause it is

it still exists in [email protected]. i have try each solution above, but don't work for me. Is there a perfect solution to this problem?

For people complaining about "me too" and +1s, don't say it is not useful because it is, nobody is looking at this issue and the bot will just close the issue if there's no reply. So yes, keep the issue alive, github will hide similar messages.

FWIW, I was a hitting different issue that led me here. Specifically, when running on an actual iOS device, I was receiving a red-box message that "Connection to http://my-ip-address:8081/debugger-proxy?role=client timed out. Are you running node proxy? If you are running on the device, check if you have the right IP address in RCTWebSocketExecutor.m.

I noticed that this issue occurred when I switched between two different networks (call them A and B). When running on network B, the IP address in the message above was from network A. I finally figured out that if I delete the test application from the iOS device, then re-run, the app would then correctly use network B and the issue was resolved. So, now I know that when I change networks, I simple delete the test app (and its data) to resolve this issue.

There is probably a more precise way to resolve this, but deleting the app worked fine for me. Clearly something on the iOS device is remembering the IP address from a different network and trying to reuse it.

Hopefully this post will save someone some time!

Was this page helpful?
0 / 5 - 0 ratings