Tutorial Socket Programming :Example Creating the Socket connection in java

java.net package is used for Socket Programming in java.

Lets look at the java.net.Socket class which is inherited from java.lang.Object.

An instance of the SocketImpl class do all the work for Socket.

Here is a example to test the socket connection :


import java.io.IOException;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.IllegalBlockingModeException;
import java.net.SocketTimeoutException;

public class SocketTest {

public static void main( String [] args ) {

int default_timeout = 2000; // timeout used if timeout not provided

if( isInputInvalid( args ) ) {

System.err.println("Usage: java TestConnection [ remotehost ip address ] [ port ] [timeout_seconds]");
System.exit( -1 );

} else if ( args.length == 3 ){
try {
default_timeout = Integer.parseInt( args[2] ) * 1000;

} catch( NumberFormatException nfe ){
System.out.println(" Please enter valid timeout seconds ");
System.err.println("Usage: java TestConnection [ remotehost ip address ] [ port ] [timeout_seconds]");

}
}

String host = args[0];
String port = args[1];

System.out.println(" Testing connection for "+ host +" with "+ port );

Socket socket = new Socket(); // Unconnected socket, with the system-default type of SocketImpl.
InetSocketAddress endPoint = new InetSocketAddress( host,
Integer.parseInt( port )  ); //Creates a socket address from a hostname and a port number.

if ( endPoint.isUnresolved() ) { // Checks wether the address has been resolved or not.

System.out.println(" Not able to resolve host " + endPoint );

} else try {

socket.connect(  endPoint , default_timeout);
System.out.printf("Connected:    %s  \n "+ endPoint.getHostName() +"",  endPoint );

} catch( IOException ioe ) {

System.out.printf("Failed to connect:    %s message: %s - %s \n",
endPoint , ioe.getClass().getSimpleName(),  ioe.getMessage());

}catch( IllegalBlockingModeException ibme ) {
//His socket has an associated channel, and the channel is in non-blocking mode
System.out.printf("Failed to connect:    %s message: %s - %s \n",
endPoint , ibme.getClass().getSimpleName(),  ibme.getMessage());

} catch( IllegalArgumentException iae ) {
// Endpoint is null or is a SocketAddress subclass not supported by this socket
System.out.printf("Failed to connect:    %s message: %s - %s \n",
endPoint , iae.getClass().getSimpleName(),  iae.getMessage());

}  finally {
if ( socket != null ) try {
socket.close();
} catch( IOException ioex ) {}

}

}
private static final boolean isInputInvalid( String [] args ) {
if ( args.length < 2
|| ( args.length >= 2 && !args[1].matches("\\d+") ) ){

//IP Address validation etc to be added if needed
return true;
}else{
return false;
}
}

}
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

2 comments:

  1. bertram custom house build27 January 2015 at 04:13

    I read this piece of writing fully about the resemblance of most up-to-date and preceding technologies, it's awesome article.|

    ReplyDelete
  2. hi.
    nice explanation for java programming.
    can u pl help me sort out one network problem in java its all about INETSOCKETADDRESS.
    i

    ReplyDelete