Example
public class ConnectSocketExample {
private int HTTP_PORT = 80;
/**
* example method to create unconnected socket
* then connect to it
* at end return connected socket
*
* @param httpHostName - endpoint host name fot socket connection
* @throws IOException - if the socket is already connected or an error occurs while connecting.
*/
protected Socket connectSocket(String httpHostName) throws IOException {
// define local variable for socket and create unconnected socket
Socket socket = new Socket();
// create iNet address for socket
InetSocketAddress inetSocketAddress = new InetSocketAddress(httpHostName, HTTP_PORT);
// connect socket to inet address (end point )
socket.connect(inetSocketAddress);
// return connected socket for later use
return socket;
}
/**
* public method for try to create connected to goole.com http port socket
* and with check and system out print if this try was successful
**/
public void createAndCheckIfConnected() {
try {
Socket connectedSocket = connectSocket("google.com");
boolean connected = connectedSocket.isConnected();
System.out.print("Socket is:" + (!connected ? " not" : "" + " connected"));
} catch (IOException e) {
e.printStackTrace();
}
}
}