Android Lollipop Wifi Socket java.net.ConnectException ETIMEDOUT
I am trying to connect to a socket like this:
try {
Server = "192.168.0.10";
port = 7000;
System.out.println("SOCKET: Create Socket: " + Server+ ":" + port);
socket = new Socket(Server, port);
System.out.println("SOCKET: Created Socket: " );
out = socket.getOutputStream();
in = socket.getInputStream();
return true;
} catch (IOException ex) {
System.out.println("SOCKET: CATCH: " + ex.getLocalizedMessage());
return false;
}
This works fine on my Android 4.2 device. If I test the same code on Android Lollipop (5.x), I get the following errors:
05-20 08:25:59.592: E/Con(8167): java.net.ConnectException: failed to connect to /192.168.0.10 (port 7000): connect failed: ETIMEDOUT (Connection timed out)
05-20 08:25:59.592: E/Con(8167): at libcore.io.IoBridge.connect(IoBridge.java:124)
05-20 08:25:59.592: E/Con(8167): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
05-20 08:25:59.592: E/Con(8167): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
05-20 08:25:59.592: E/Con(8167): at java.net.Socket.startupSocket(Socket.java:590)
05-20 08:25:59.592: E/Con(8167): at java.net.Socket.tryAllAddresses(Socket.java:128)
05-20 08:25:59.592: E/Con(8167): at java.net.Socket.<init>(Socket.java:178)
05-20 08:25:59.592: E/Con(8167): at java.net.Socket.<init>(Socket.java:150)
In both cases, my Android devices are connected to the same device via Wi-Fi. Does anyone know the problem with Lollipop?
Thank!!
EDIT: WORKAROUND: Well, I noticed strange behavior: if I disconnect the mobile internet data, the socket is created! But I need mobile data, so this is not a satisfactory solution ... Any ideas on how to create a socket with mobile data activated?
source to share
We faced the same problem. We solved it like this:
ConnectivityManager conMan = (ConnectivityManager) Context.getSystemService(CONNECTIVITY_SERVICE);
NetworkRequest.Builder nb = new NetworkRequest.Builder();
nb.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
conMan.requestNetwork(nb.build(), new ConnectivityManager.NetworkCallback() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onAvailable(Network network) {
Socket s = new Socket();
network.bindSocket(s);
s.bind(new InetSocketAddress(server, port));
}
});
By using Network.bindSocket (Socket), you can actively select the network you want to use for that socket. This is necessary because since Lollipop the system defaults to a network with an Internet connection.
source to share