I am trying to make a TCP connection in my Xamarin Android app using System.Net.Sockets.TcpClient
.
The connection is perfectly fine when I do it on a conso
Regardless of whether or not you can do network operations on the main thread (as commented by @ÖmerBaş,) you have a much more basic problem with network concepts causing your error.
127.0.0.1 always refers to the machine the program is running on.
When you run your code in the console, 127.0.0.1 refers to the PC you are working on and presumably where the TCP server is running.
When you run the code on Android, 127.0.0.1 refers to the Android device itself. Your error message says "Connection refused." That's because your TCP-Server isn't running on the Android device. It is running on your PC.
You need to know what IP address your Android device can use to connect to your PC.
If you are using a real Android device, you will need to have your Android device connect to the same network as your PC via WiFi. Then you can use your PC's IP address in your code.
For the simulators, there's a couple of possibilities:
(Simulator addresses take from here.)
Make sure to bind your TCP service to all IP addresses, not just 127.0.0.1.
An alternative solution is to use adb to set up port forwarding on your Android device (whether simulated or real.)
I think the "network access on the main thread" thing is more a problem of "should not" rather than "cannot." The question referred to by Ömer Baş shows "permission denied" errors rather than something pointing to a threading problem.