Tag Archive: Java


The chasm between the Object Oriented approach followed by almost all the language or platforms on which applications are developed and the language used by database servers (SQL) is considerably big. This divide exists because the application development languages/platforms deals with objects, attributes and classes whereas SQL deals with rows, columns and tables. There are many frameworks that provide the means to bridge this gap. These frameworks do so by mapping the database artefacts to their object-oriented counterparts. Such frameworks are called Object Relational Mapping or ORM frameworks. In the world of Java, Hibernate is one of the widely used ORM frameworks. In its 2.x version, Hibernate depended on XML files to map Java artefacts to Database artefacts. However, in 3.0 and above, Hibernate provides annotations as an alternative to the XML based mapping. Use of annotations in Hibernate will be the focus of this discussion. The first section will be about the whys and wherefores of annotations in Hibernate. In the second section, the focus will be on the steps required to use the annotations for relational-object mapping. The third section will be about a real world example that makes use of Hibernate 3 and annotations.

Annotations in Hibernate – the Whys and Wherefores

To understand annotation used in Hibernate, two aspects need to be understood. They are

1. Annotations in Java

2. Annotations in Hibernate

Between these two aspects, former of the deals with annotations in general and  later  deals with annotations specific to Hibernate. Here are the details.

1. Annotations in Java
Before we move onto how Hibernate makes use of annotations, let us take a bird’s eye view of what
annotations are. By definition Annotations are “is a special form of syntactic metadata that can be added to
Java source code. Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc
tags, Java annotations can be reflective in that they can be embedded in class files generated by the
compiler and may be retained by the Java VM to be made retrievable at run-time”. From the definition it is
clear that Annotations in Java have two components. They are:

a. The Metadata

It is of the form “@” where is the name of the metadata. Annotations are metadata of
this form. They can be used to decorate classes, methods, variables, parameters and packages. For
example, the following statements tell the metadata processor that the method is overriding the method
of the base class

@override

Public void display(String name)

{

System.out.println(“Hello “+ name);

}

One important point to keep in mind is that annotations are not discarded after compilation to byte code.
By applying certain policies, they can be retained during runtime. This is not the case with Javadoc tags.
Once compiled, they are lost. In other words, the byte code does not contain the Javadoc tags.

b. The Metadata Processor

It comes into picture during compilation. Metadata Processors or Annotation Processors, as they are
commonly called, are plug-ins to the compiler. A Processor can do a variety of things for the annotated
code including generation of source code files. One important point about Processors is that cannot do
any modification to the annotated code.

That completes the bird’s eye view of Annotations. Let us move onto Annotations in Hibernate.

2. Annotations in Hibernate

Any ORM does four basic mapping. They are:

a. Table mapping

b. Column mapping

c. Key mapping

d. Relationship mapping

How each framework performs the mapping is what makes them different or unique, so is how each
framework wants mapping to be described. Hibernate allows the mapping to be described using either XML
file or Annotations. These two options cannot be mixed and matched. Let us see how Hibernate uses
Annotations for describing the mappings. However, among the four mappings mentioned above, Relationship
mapping will not be a part of this discussion as it is out scope.

a. Table mapping

To map a table, @Table is used. It takes the name of the table that is passed using the name property of the
@Table annotation. For example, the following statements map a table named ‘Products’ to a class named
Product

@Table (name=”Products”)

public class Products {

//…other declarations

}

b. Column mapping

The annotation used to map a column of a table to an attribute of a class is @Column. The name of the
column of the table to be mapped is passed to the annotation using the name property of the @Column.
Following statements map ‘Product_name’ column of ‘Products’ table to ‘name’ field of ‘Products’ class.

@Table (name=”Products”)

public class Products {

//…other declarations

@Column (name=”Product_name”)

String name;

}

c. Key mapping:

Key, in this context, means Primary key of the table being mapped. The @Id annotation is used to map a
field of a class to the Primary key column of the table. @Id is used along with @Column. More specifically,
@Id is used for a field that is already decorated with @Column. The reason is that unless a field is mapped to
a column, the field cannot be considered for Primary key mapping. For example, the following statements
map a field named ‘productId’ to the primary key of the table ‘Products’

@Table (name=”Products”)

public class Products {

//…other declarations

@Id

@Column (name=”Product_id”)

long productId;

}

That completes the whys and wherefores of Annotations in general and how annotations are used in
Hibernate. Let’s move on to the steps for using annotations for mapping.

Introducing Android SDK

Smart mobiles are gaining wider acceptance with each passing day. The market acceptance is resulting in increased demand for easier as well as flexible programming platforms, which in turn has resulted in new players entering the mobile SDK arena. The latest entrant is Google with its Android platform and corresponding SDK, which will be the focus of this discussion. The first section will be about whys and wherefores of Android. In the second section, the focus will be on the steps required in developing a basic Android application. The last section will focus on developing an application based on the steps described in the second section. That sets the agenda for this discussion.

Android – the Whys and Wherefores:

By definition “Android is a software stack for mobile devices that includes an operating system, middleware and key applications”. In other words, Android not only provides a runtime environment but also an SDK to develop applications aimed at the runtime environment. The Android stack consists of the following layers:

1. Kernel

2. Android Runtime

3. Libraries

4. Application Framework

5. Applications

The layers enumerated above are in bottom-up fashion i.e. Kernel forming the bottom most layer and Applications forming the topmost layer. Even though, Android is termed as a software stack, it, more or less exhibits characteristics of an Operating System that will be evident from details of the layers.

1. Kernel

It forms the foundation of Android. Kernel does all the low-level interactions at the hardware level. Kernel achieves this via the device drivers that are present at this layer. Android makes use of Linux kernel 2.6. The core services provided by the kernel include security, memory management, process management and network stack and driver model. In short, the kernel acts as a layer that encapsulates the interaction between other layers and hardware.

2. Android Runtime:

Runtime contains basic libraries that are required to run an application. These libraries provide most of the functionalities provided by Java libraries. Android applications target Dalvik virtual machine (VM), which essentially is the runtime.  Each application runs in its own process, each with its own instance of Dalvik VM. The runtime depends on the kernel for functionalities such as system-level threading and low-level memory management.

3. Libraries:

The various components and sub-systems of Android are included in the stack as a set of C/C++ libraries. The library includes System library, Media libraries, Surface Manager Library, OpenGL library etc. The functionalities of these libraries are provided to the developer through the Application Framework Layer.

4. Application Framework:

This layer exposes the functionalities provided by the Libraries layer to the developer. The Libraries layer contains C/C++ API. The Application Framework layer wraps those API and exposes it to the developer as Java API. The Application Framework consists of components such as Activity Manager, Window Manager, Content Providers, View Systems etc. Applications are built upon the services provided by these components.

5. Applications:

This is topmost layer of the Android stack. This layer contains pre-built applications such as email client, SMS program, maps, browser etc. The custom applications deployed by the user sit in this layer.

That completes the bird-eye view of the Android. In the next section, the steps to develop an Android application will be enumerated. From here on, Android would mean the complete stack and Android SDK would mean the tools and libraries required for developing applications for Android.

Developing an Android Application – Step-by-Step:

An Android application can be developed either by using Eclipse plug-in or by using tools provided alongwith the SDK. In this discussion, the second way will be used. The advantage of using the second step is that one will not be tied up with a particular IDE. Following are the steps for developing application without using Eclipse:

1. Generate Project Directories and Stubs

2. Develop UI logic

3. Compile and Deploy the Project

For all the steps except second, SDK provide tools. Here are the details.

1. Generate Project Directories and Stubs:

First step is to generate the directory structure and the source code stubs. To achieve this end, Android SDK provides a tool named activityCreator.py. It is a Python script. The script also creates an ant build file that can later be used to compile the application. The option that one needs to keep in mind is the out option. Using the out option, the name of the project directory can be specified. For example, to create a HelloWorld project with ‘HelloWorld’ as the directory and org.me.android.hello.HelloWorld as the class, the command will be

activityCreator.py –out HelloWorld com.android.hello.HelloWorld

2. Develop UI logic:

Next step is to develop the UI of the application. The activityCreator.py script created the stubs. To develop the UI, the generated source-code stub needs to be edited. It can be found in the src folder of the generated application folder. For example, the stub generated for the HelloWorld can be found inside HelloWorld\src folder. The auto-generated class will be as follows

public class HelloWorld extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

}

}

The UI in Android is composed of hierarchies of Views. Each component is a view. Some of the views act as containers. One of the most commonly used views is TextView. It provides the functionality of a label. To instantiate an object of the TextView class, an instance of the Android Context is required.

Context is a handle to the system. It provides access to the services such as accessing database, resolving resource bundles to their locales etc. Activity class is a sub-class of Context class. Any class that is generated by the script inherits Activity. Hence, instance of Context can be passed by passing the instance of the generated class using this keyword. For example, to instantiate an object of TextView class named textView, the statement will be

TextView textView = new TextView(this);

Next step is to display a text value using the TextView. To do so, setText method of TextView class can be used. For example, the following statement will display “Hello World”

textView.setText(“Hello World”);

Last step in displaying the text label is to add instance of TextView to the onscreen display. setContentView() method of Activity class can be used to connect or add instance of TextView class. For example, to add textView to the onscreen display, the statement will be

setContentView(textView);

Next, let us see how to compile the project and deploy it.

3. Compile and Deploy the Project:

To compile the project, the only tool needed is ant. In the folder containing the
build.xml file, one has to just give the following command

ant

The ant tool will take the build.xml file and generate the class files. Then it will
package them into an .apk file. It is Android asset package file. The next step is to
deploy the .apk file. To do so, adb tool can be used. The install option of the adb
tool tells the tool to install the package into the simulator. The parameter that
needs to be passed to the tool is the path to the package.

That completes this section. Next, a small application will be developed based on the steps detailed in this section.

Android SDK – In Real World:

The application to be developed will have following features:

1. A widget, which will be a button

2. An event-handler for the button

3. A dialog box that will be shown when the button is clicked

The application, though simple, will be the base for future discussions. So lets get started. First step is to create the application structure. The name of the application will be AndroidNotepad. Using the createActivity.py the structure can be created. Once the structure is created, the AndroidNotepad.java will contain the following code

package org.me;

import android.app.Activity;

import android.os.Bundle;

public class AndroidNotepad extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(button);

}

}

Next, a button needs to be added. That can be done as shown in the code

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

public class AndroidNotepad extends AndroidNotepad {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

setContentView(button);

}

}

The next step is to capture the click event of the button. To do so, the OnClickListener interface needs to be implemented. The interface can be found in View package. To implement the OnClickListener interface, one needs to override the onClick() method. The following code implements the OnClickListener for the button

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

setContentView(button);

}

public void onClick(View arg0) {

}

}

To attach the event handler to the button, the setOnClickListener() method of Button can be used.

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

button.setOnClickListener(this);

setContentView(button);

}

public void onClick(View arg0) {

}

}

Lastly, the code to display the dialog box when the button is clicked is as under

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

button.append(“Click”);

button.setOnClickListener(this);

setContentView(button);

}

public void onClick(View arg0) {

showAlert(“Button”, 0, “Button Clicked”, “OK”, true);

}

}

To show the dialog box showAlert method is used. More about the showAlert() method in the future discussions. That brings us to the end of this discussion. This discussion has just touched the tip of the iceberg that is Android. The next part of this discussion will be about using XML based definitions for the UI. Till then…

Smart mobiles are gaining wider acceptance with each passing day. The market acceptance is resulting in increased demand for easier as well as flexible programming platforms, which in turn has resulted in new players entering the mobile SDK arena. The latest entrant is Google with its Android platform and corresponding SDK, which will be the focus of this discussion. The first section will be about whys and wherefores of Android. In the second section, the focus will be on the steps required in developing a basic Android application. The last section will focus on developing an application based on the steps described in the second section. That sets the agenda for this discussion.

Android – the Whys and Wherefores:

By definition “Android is a software stack for mobile devices that includes an operating system, middleware and key applications”. In other words, Android not only provides a runtime environment but also an SDK to develop applications aimed at the runtime environment. The Android stack consists of the following layers:

1. Kernel

2. Android Runtime

3. Libraries

4. Application Framework

5. Applications

The layers enumerated above are in bottom-up fashion i.e. Kernel forming the bottom most layer and Applications forming the topmost layer. Even though, Android is termed as a software stack, it, more or less exhibits characteristics of an Operating System that will be evident from details of the layers.

1. Kernel

It forms the foundation of Android. Kernel does all the low-level interactions at the hardware level. Kernel achieves this via the device drivers that are present at this layer. Android makes use of Linux kernel 2.6. The core services provided by the kernel include security, memory management, process management and network stack and driver model. In short, the kernel acts as a layer that encapsulates the interaction between other layers and hardware.

2. Android Runtime:

Runtime contains basic libraries that are required to run an application. These libraries provide most of the functionalities provided by Java libraries. Android applications target Dalvik virtual machine (VM), which essentially is the runtime.  Each application runs in its own process, each with its own instance of Dalvik VM. The runtime depends on the kernel for functionalities such as system-level threading and low-level memory management.

3. Libraries:

The various components and sub-systems of Android are included in the stack as a set of C/C++ libraries. The library includes System library, Media libraries, Surface Manager Library, OpenGL library etc. The functionalities of these libraries are provided to the developer through the Application Framework Layer.

4. Application Framework:

This layer exposes the functionalities provided by the Libraries layer to the developer. The Libraries layer contains C/C++ API. The Application Framework layer wraps those API and exposes it to the developer as Java API. The Application Framework consists of components such as Activity Manager, Window Manager, Content Providers, View Systems etc. Applications are built upon the services provided by these components.

5. Applications:

This is topmost layer of the Android stack. This layer contains pre-built applications such as email client, SMS program, maps, browser etc. The custom applications deployed by the user sit in this layer.

That completes the bird-eye view of the Android. In the next section, the steps to develop an Android application will be enumerated. From here on, Android would mean the complete stack and Android SDK would mean the tools and libraries required for developing applications for Android.

Developing an Android Application – Step-by-Step:

An Android application can be developed either by using Eclipse plug-in or by using tools provided alongwith the SDK. In this discussion, the second way will be used. The advantage of using the second step is that one will not be tied up with a particular IDE. Following are the steps for developing application without using Eclipse:

1. Generate Project Directories and Stubs

2. Develop UI logic

3. Compile and Deploy the Project

For all the steps except second, SDK provide tools. Here are the details.

1. Generate Project Directories and Stubs:

First step is to generate the directory structure and the source code stubs. To achieve this end, Android SDK provides a tool named activityCreator.py. It is a Python script. The script also creates an ant build file that can later be used to compile the application. The option that one needs to keep in mind is the out option. Using the out option, the name of the project directory can be specified. For example, to create a HelloWorld project with ‘HelloWorld’ as the directory and org.me.android.hello.HelloWorld as the class, the command will be

activityCreator.py –out HelloWorld com.android.hello.HelloWorld

2. Develop UI logic:

Next step is to develop the UI of the application. The activityCreator.py script created the stubs. To develop the UI, the generated source-code stub needs to be edited. It can be found in the src folder of the generated application folder. For example, the stub generated for the HelloWorld can be found inside HelloWorld\src folder. The auto-generated class will be as follows

public class HelloWorld extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

}

}

The UI in Android is composed of hierarchies of Views. Each component is a view. Some of the views act as containers. One of the most commonly used views is TextView. It provides the functionality of a label. To instantiate an object of the TextView class, an instance of the Android Context is required.

Context is a handle to the system. It provides access to the services such as accessing database, resolving resource bundles to their locales etc. Activity class is a sub-class of Context class. Any class that is generated by the script inherits Activity. Hence, instance of Context can be passed by passing the instance of the generated class using this keyword. For example, to instantiate an object of TextView class named textView, the statement will be

TextView textView = new TextView(this);

Next step is to display a text value using the TextView. To do so, setText method of TextView class can be used. For example, the following statement will display “Hello World”

textView.setText(“Hello World”);

Last step in displaying the text label is to add instance of TextView to the onscreen display. setContentView() method of Activity class can be used to connect or add instance of TextView class. For example, to add textView to the onscreen display, the statement will be

setContentView(textView);

Next, let us see how to compile the project and deploy it.

3. Compile and Deploy the Project:

To compile the project, the only tool needed is ant. In the folder containing the
build.xml file, one has to just give the following command

ant

The ant tool will take the build.xml file and generate the class files. Then it will
package them into an .apk file. It is Android asset package file. The next step is to
deploy the .apk file. To do so, adb tool can be used. The install option of the adb
tool tells the tool to install the package into the simulator. The parameter that
needs to be passed to the tool is the path to the package.

That completes this section. Next, a small application will be developed based on the steps detailed in this section.

Android SDK – In Real World:

The application to be developed will have following features:

1. A widget, which will be a button

2. An event-handler for the button

3. A dialog box that will be shown when the button is clicked

The application, though simple, will be the base for future discussions. So lets get started. First step is to create the application structure. The name of the application will be AndroidNotepad. Using the createActivity.py the structure can be created. Once the structure is created, the AndroidNotepad.java will contain the following code

package org.me;

import android.app.Activity;

import android.os.Bundle;

public class AndroidNotepad extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(button);

}

}

Next, a button needs to be added. That can be done as shown in the code

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

public class AndroidNotepad extends AndroidNotepad {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

setContentView(button);

}

}

The next step is to capture the click event of the button. To do so, the OnClickListener interface needs to be implemented. The interface can be found in View package. To implement the OnClickListener interface, one needs to override the onClick() method. The following code implements the OnClickListener for the button

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

setContentView(button);

}

public void onClick(View arg0) {

}

}

To attach the event handler to the button, the setOnClickListener() method of Button can be used.

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

button.setOnClickListener(this);

setContentView(button);

}

public void onClick(View arg0) {

}

}

Lastly, the code to display the dialog box when the button is clicked is as under

package org.me;

import android.app.Activity;

import android.os.Bundle;

import android.widget.Button;

import android.view.*;

public class AndroidNotepad extends Activity implements View.OnClickListener {

/** Called when the activity is first created. */

Button button;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

button =new Button(this);

button.append(“Click”);

button.setOnClickListener(this);

setContentView(button);

}

public void onClick(View arg0) {

showAlert(“Button”, 0, “Button Clicked”, “OK”, true);

}

}

To show the dialog box showAlert method is used. More about the showAlert() method in the future discussions. That brings us to the end of this discussion. This discussion has just touched the tip of the iceberg that is Android. The next part of this discussion will be about using XML based definitions for the UI. Till then…

Socket Programming in Java

In a world which is wired, standalone applications are becoming obsolete. The felicitators for the connectivity of applications, at low-level, are sockets. Any language, whether high-level or low-level, must provide APIs to handle sockets if they desire wide acceptance. Java is no exception. Java facilitates socket programming through its java.net package. And true to its philosophy, it abstracts out the most of the low-level ‘nitty-gritty’ associated with socket and provides a clean object-oriented API to work with. In this article I would discuss about how to use the java.net package, in order to net enable any application (CLI or GUI based) with TCP based sockets. The first section would be about what sockets are and how they have been supported in Java. In the second section, I would enumerate the steps to use sockets within an application. In the last section I would develop a real world application using sockets. That sets the course for this discussion.

Sockets – What are They:

If one looks up the definition, the most common one would be “A socket is one endpoint of a two-way communication link between two programs running on the network”. To put it differently, it is through sockets that applications access the network and transmit data. As varied are the purpose and platforms of applications, so are the types of sockets. There are three types of sockets:

1. Unix Domain Sockets

2. Internet Domain Sockets

3. NS Domain Sockets

Of these only Internet Domain Sockets are supported across all the platforms. So to maintain the cross-platform characteristic intact, Java supports only Internet Domain Sockets. The next question that arises is what are the characteristics of an Internet Domain Socket and what protocols are supported by it? Here are the answers:

Internet Domain Sockets:

By definition “An Internet socket (or commonly, a socket or network socket), is a communication end-point unique to a machine communicating on an Internet Protocol-based network, such as the Internet”. All applications communicating through the internet use network socket. The feature that distinguishes network socket from other sockets is the protocols that it supports. The supported protocols are:

1. TCP

2. UDP

3. Raw IP

The difference between them is based on whether the protocol is connection oriented or not. Here are the details:

1. TCP:

It is one of the core protocols of internet protocol suite. The protocol guarantees reliable and in-order (correct order of packets) delivery of data from sender to receiver. In other words it’s reliable. Second aspect of TCP is that it is connection oriented. That means, TCP requires that connection be made between sender and receiver before data is send. The socket associated with TCP is known as Stream Socket.

2. UDP:

Like TCP, UDP is also one of the core protocols of IP suite. However, unlike TCP, it neither guarantees in-order delivery of data nor does it requires a connection being established for sending the data. To put in short, UDP is unreliable and connectionless protocol. Sockets associated with UDP are known as Datagram Sockets.

3. Raw IP:

It is the non-formatted protocol as opposed to the TCP and UDP. It works at network and transport layers. A socket associated with Raw IP is known as Raw Sockets. UDP and TCP sockets just receive the payload or the data whereas Raw Sockets receive the header info of the packet along with the data. The downside of Raw Sockets is that it is tightly coupled with the implementation provided by the underlying host operating system.

Next lets see how Java places the different type of sockets in its libraries.

Sockets in Java:

Like all other functionalities provided by Java, functionalities to work with sockets are also ‘packaged’ as package and its classes. Following are the package and its main classes that help in accessing sockets:

1. java.net package

2. ServerSocket

3. Socket

Among the above Java, abstracts out, most of the low-level aspects of socket programming. Here are the details:

1. java.net package:

It contains all the classes required to create network enabled applications. ServerSocket and Socket are also part of this package. Apart from these classes, it also contains classes to connect to web server, create secured sockets etc.

2. ServerSocket:

This class provides server sockets or sockets at server side. Such sockets wait for requests over the network. Once such requests arrive, server socket performs operation based on the request and may return a result. The ServerSocket class wraps most of the options required to create server-side sockets.

3. Socket:

This class provides client-side socket or simply sockets. They are at the client side connecting to the server and sending the request to the server and accepting the returned result. Just like ServerSocket exposes only the compulsory parameters required to create a server-side socket, similarly, Socket asks the user to provide only those parameters that is most necessary.

That’s all about sockets and Java. In the next section, I would discuss about the steps involved in creating socket based applications.

Socket Programming- Step By Step:

Any net enabled application has two important parts – the code that executes at client-side and the code that executes at server-side. So the steps to use functionality of sockets can be partitioned into two major steps:

1. The Server or the server-side code

2. The Client or the client-side code

The multi-threaded nature of former can always be guaranteed whereas the later may or may not be multi-threaded.

1. The Server:

The main function of the server is to wait for the incoming requests and once such a request comes, service it. So the code to implement Server can be further broken down to following steps:

i. Establish a Server that monitors a particular port:

This is done by creating an instance of the ServerSocket class. There are four different ways to create an instance of ServerSocket. They are –

a. ServerSocket() – it simply sets the implementation that means everything is

taken as default values.

b. ServerSocket(int port)- it creates a server-side socket and binds the socket

to the given port no.

c. ServerSocket(int port, int backlog) – it not only binds the created socket to

the port but also create a queue of

length specified by the no. passed as

backlog parameter.

d. ServerSocket(int port, int backlog, InetAddress bindAddr)-

it creates a server-side socket that is bound to the specified port no. with the queue of length specified by backlog and bound to the address specified by bindAddr argument.

So to create a socket bound to port no. 8888 with a backlog queue of size 5 and bound with address of local host the statement would be:

ServerSocket server = new ServerSocket(8888, 5, InetAddress.getLocalHost() );

One point to keep in mind is that the above mentioned constructors return TCP sockets and not UDP sockets.

ii. Listen for incoming Requests:

Next step is to tell the newly created server socket to listen indefinitely and accept incoming requests. This is done by using the accept() method of ServerSocket class. When a request comes, accept() return a Socket object representing the connection. In code it would be:

Socket incoming = server.accept();

iii. Communicating with the Socket:

In other words, communicating with the Socket means reading from and writing to the Socket object. To communicate with a Socket object two tasks have to be performed. Firstly the Input and Output stream corresponding to the Socket object has to be obtained. That can be done by using getInputStream() and getOutputStream() methods of Socket class. In code it would be:

BufferedReader in = new BufferedReader

(new InputStreamReader(incoming.getInputStream()));

PrintWriter out = new PrintWriter

(incoming.getOutputStream(), true /* autoFlush */);

The second task is to read from and write to the Socket object. Since the communication has to continue till the client breaks the connection, the reading from and writing to is done within a loop as thus:

boolean done = false;

while (!done)

{

String line = in.readLine();

if (line == null) done = true;

else

{

out.println(“Echo: ” + line);

if (line.trim().equals(“BYE”))

done = true;

}

}

The actual syntax for reading and writing is not different from the I/O done for simple files.

iv. Closing the connection:

Once the client breaks the connection or stops sending the request, the Socket object representing the client has to be closed. This can be done by calling close() method on the Socket object. The statement would be:

incoming.close();

That’s how a Server is coded. Next section deals with creating a client.

2. The Client:

The main purpose of client is to connect to the server and communicate with it using the connection. So to code a client has following steps:

i. Connect to the Server:

Connecting with the server can be accomplished in two steps:

a. Creating a Socket object:

The socket at client side just needs to know the host name (the name of the machine where server is running) and the port where the server is listening. To create a Socket object, there are seven constructors provided by the Socket class of which the most commonly used are:

  • Socket() – Creates a new instance of Socket without connecting to

host

  • Socket(InetAddress address, int port) – creates a new Socket object and connects to the port specified at the given address.

  • Socket(java.lang.String host, int port) – same as first one except that instead of address, host name is used.

So to create a Socket object that connects to ‘localhost’ at 8888, the statement would be:

Socket s=new Socket(“localhost”,8888);

b. Connect to the Server:

This step comes into picture, if no argument constructor is used. It takes object of SocketAddress object as argument. So to connect to localhost at port 8888, the code will be:

Socket s= new Socket();

s.connect(new SocketAddress(“localhost”,8888));

ii. Communicating with the Server:

Communicating with the server using a socket at client side is not different when compared with how server communicates with client. Firstly, the input and output streams connected with the Socket object is to be retrieved thus:

BufferedReader in = new BufferedReader

(new InputStreamReader(s.getInputStream()));

PrintWriter out = new PrintWriter

(s.getOutputStream(), true /* autoFlush */);

Then read and write using the corresponding streams. For example, if the client just waits for the data sent by the server, the code would be

boolean more = true;

while (more)

{

String line = in.readLine();

if (line == null)

more = false;

else

System.out.println(line);

}

That’s all about steps in creating network enabled application. In the next section I would be developing a file server application with multi-threading to handle multiple clients.

Socket Programming – In Real World:

Its time to put theory to practice. The file server to be developed would provide the following services:

1. List the files that can be downloaded

2. Send the selected file

3. Process each request in a separate thread

It is from the solution to an exercise from Professor David Eck’s on-line textbook, published under an open content license at http://math.hws.edu/eck/cs124/javanotes4/c10/ex-10-4-

answer.html

There are two classes that form the server:

1. FileServer – sets up the server

2. ConnectionHandler – services the requests for sending of file to clients

Lets look at the implementation. First comes the FileServer class. It does the following tasks:

1. Checks the existence of the directory name specified

2. Sets up the server

3. Delegates the requests to be handled to object of ConnectionHandler class.

Following is the implementation of the class:

import java.net.*;

import java.io.*;

public class FileServer {

static final int LISTENING_PORT = 3210;

public static void main(String[] args) {

File directory; // The directory from which the

// gets the files that it serves.

ServerSocket listener; // Listens for connection requests.

Socket connection; // A socket for communicating with

// a client.

/* Check that there is a command-line argument.

If not, print a usage message and end. */

if (args.length == 0) {

System.out.println(“Usage: java FileServer <directory>”);

return;

}

/* Get the directory name from the command line, and make

it into a file object. Check that the file exists and

is in fact a directory. */

directory = new File(args[0]);

if ( ! directory.exists() ) {

System.out.println(“Specified directory does not exist.”);

return;

}

if (! directory.isDirectory() ) {

System.out.println(“The specified file is not a directory.”);

return;

}

/* Listen for connection requests from clients. For

each connection, create a separate Thread of type

ConnectionHandler to process it. The ConnectionHandler

class is defined below. The server runs until the

program is terminated, for example by a CONTROL-C. */

try {

listener = new ServerSocket(LISTENING_PORT);

System.out.println(“Listening on port ” + LISTENING_PORT);

while (true) {

connection = listener.accept();

new ConnectionHandler(directory,connection);

}

}

catch (Exception e) {

System.out.println(“Server shut down unexpectedly.”);

System.out.println(“Error: ” + e);

return;

}

} // end main()

:

:

}

Next comes the ConnectionHandler class. The important aspect of this class is that it is a static inner class of FileServer class. The tasks carried out by this class are:

1. Start the thread – it is done in the constructor of the class

2. Send the list of downloadable files – the sendIndex() method contains the logic

for sending the list.

3. Sending the selected file – this task is performed by sendFile() method

4. Communication with client – this task is done in the run() method. This method

also calls other methods as required.

Following is the implementation. The class is

import java.net.*;

import java.io.*;

public class FileServer {

static final int LISTENING_PORT = 3210;

public static void main(String[] args) {

File directory; // The directory from which the

// gets the files that it serves.

ServerSocket listener; // Listens for connection requests.

Socket connection; // A socket for communicating with

// a client.

/* Check that there is a command-line argument.

If not, print a usage message and end. */

if (args.length == 0) {

System.out.println(“Usage: java FileServer <directory>”);

return;

}

/* Get the directory name from the command line, and make

it into a file object. Check that the file exists and

is in fact a directory. */

directory = new File(args[0]);

if ( ! directory.exists() ) {

System.out.println(“Specified directory does not exist.”);

return;

}

if (! directory.isDirectory() ) {

System.out.println(“The specified file is not a directory.”);

return;

}

/* Listen for connection requests from clients. For

each connection, create a separate Thread of type

ConnectionHandler to process it. The ConnectionHandler

class is defined below. The server runs until the

program is terminated, for example by a CONTROL-C. */

try {

listener = new ServerSocket(LISTENING_PORT);

System.out.println(“Listening on port ” + LISTENING_PORT);

while (true) {

connection = listener.accept();

new ConnectionHandler(directory,connection);

}

}

catch (Exception e) {

System.out.println(“Server shut down unexpectedly.”);

System.out.println(“Error: ” + e);

return;

}

} // end main()

static class ConnectionHandler extends Thread {

// An object of this class is a thread that will

// process the connection with one client. The

// thread starts itself in the constructor.

File directory; // The directory from which files are served

Socket connection; // A connection to the client.

TextReader incoming; // For reading data from the client.

PrintWriter outgoing; // For transmitting data to the client.

ConnectionHandler(File dir, Socket conn) {

// Constructor. Record the connection and

// the directory and start the thread running.

directory = dir;

connection = conn;

start();

}

void sendIndex() throws Exception {

// This is called by the run() method in response

// to an “index” command. Send the list of files

// in the directory.

String[] fileList = directory.list();

for (int i = 0; i < fileList.length; i++)

outgoing.println(fileList[i]);

outgoing.flush();

outgoing.close();

if (outgoing.checkError())

throw new Exception(“Error while transmitting data.”);

}

void sendFile(String fileName) throws Exception {

// This is called by the run() command in response

// to “get <fileName>” command. If the file doesn’t

// exist, send the message “error”. Otherwise,

// send the message “ok” followed by the contents

// of the file.

File file = new File(directory,fileName);

if ( (! file.exists()) || file.isDirectory() ) {

// (Note: Don’t try to send a directory, which

// shouldn’t be there anyway.)

outgoing.println(“error”);

}

else {

outgoing.println(“ok”);

TextReader fileIn = new TextReader( new FileReader(file) );

while (fileIn.peek() != ”) {

// Read and send lines from the file until

// an end-of-file is encountered.

String line = fileIn.getln();

outgoing.println(line);

}

}

outgoing.flush();

outgoing.close();

if (outgoing.checkError())

throw new Exception(“Error while transmitting data.”);

}

public void run() {

// This is the method that is executed by the thread.

// It creates streams for communicating with the client,

// reads a command from the client, and carries out that

// command. The connection is logged to standard output.

// An output beginning with ERROR indicates that a network

// error occurred. A line beginning with OK means that

// there was no network error, but does not imply that the

// command from the client was a legal command.

String command = “Command not read”;

try {

incoming = new TextReader( connection.getInputStream() );

outgoing = new PrintWriter( connection.getOutputStream() );

command = incoming.getln();

if (command.equals(“index”)) {

sendIndex();

}

else if (command.startsWith(“get”)){

String fileName = command.substring(3).trim();

sendFile(fileName);

}

else {

outgoing.println(“unknown command”);

outgoing.flush();

}

System.out.println(“OK ” + connection.getInetAddress()

+ ” ” + command);

}

catch (Exception e) {

System.out.println(“ERROR ” + connection.getInetAddress()

+ ” ” + command + ” ” + e);

}

finally {

try {

connection.close();

}

catch (IOException e) {

}

}

}

} // end nested class ConnectionHandler

}

That completes the implementation of the File Server. The discussion has left out the UDP based sockets. I will be dealing with it in the next part. Till then…

Follow

Get every new post delivered to your Inbox.