pape pape - 5 months ago 12
Java Question

Socket tcp connection

I'm developing an application on android studio. I'm trying to open a socket connection.

When the user enters the right IP address, everything works fine, but if the address is not the right IP, the

Socket
is not connected.

But the problem is that the
Socket
does not throw an catch
Exception
, the app is running and now if the user enters the right ip address, the socket is not connected.

My question is why it does not throw an catch
Exception
if the IP address is not the right IP and how can I make it work?

Here is the code

try {
sockettcp = new Socket(Address, Port);
} catch (Exception e) {
valid = false;
}

Answer

Normal way of Socket is that it tries to connect to the given IP on the given Port.

If for some reason the IP is not the right one, the Socket will not throw an err, instead it will "timeout" trying to reconnect every minute or so (Main thread or the GUI thread).

The 4 errors that are Thrown by this type of constructor public Socket(String host, int port) are:

IOException //- if an error occurs during the connection

SocketTimeoutException //- if timeout expires before connecting

IllegalBlockingModeException //- if this socket has an associated channel, and the channel is in non-blocking mode

IllegalArgumentException //- if endpoint is null or is a SocketAddress subclass not supported by this socket

To "Fix" your problem, you can set the timeout to your value (this cannot exceed the platform default)

Socket sck = new Socket();
sck.connect(new InetSocketAddress(ip, port), timeout);

To "Check" if your Socket is connected, you could try this:

Socket.isConnected(); //Returns the connection state of the socket.

Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfully connected prior to being closed.

See the javadoc for more info about theSocket.