Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create a Network Application using Java

In this article we will see how to create a Network Application with java.

Introduction

The client/server model is an application development architecture designed to separate the presentation of data from its internal processing and storage. Java provides powerful infrastructure that enables you to develop seamless client/server programming over the network. It is achieved by using software endpoint called socket. It establishes a bidirectional communication between one or more client programs across the network.

This chapter focuses on understanding the client/server architecture. In addition, it focuses on implementing the client/server architecture by using socket programming.

Features of the Client/Server Architecture

In a restaurant, you are greeted by a variety of exotic food items on the menu, and you order a pizza. A few minutes later, you are munching a hot pizza topped with melted cheese and everything else you wanted on it. You do not know, nor do you want to know, from where the waiter got the pizza, what went into its making or how the ingredients were obtained.

The entities involved in the above example are - the delicious pizza, the waiter who took your order, the kitchen where the pizza was made, and of course, you. You are the customer or client who ordered the pizza. There was a process of creating the pizza, which was encapsulated from you. Your request was processed in the kitchen, and the waiter served the pizza to you.

What you are looking at is a client/server model. The client places a request or order to the server. The server processes the request of the client. The communication between the client and the server is an important constituent in Client/Server models and is usually through a network. The client/server model is an application development architecture designed to separate the presentation of data from its internal processing and storage. The client requests for services and the server services these requests. The requests are transferred from the client to the server over the network. The processing that is done by the server is hidden from the client. One server can service multiple clients.

The following figure displays multiple clients accessing a server.

Multiple Clients Accessing a Server

Figure 1: Multiple Clients Accessing a Server

The server and the client are not necessarily hardware components. They can be programs working on the same machine or on different machines. Consider the data entry program of an airline reservation system. The data such as the name of the passenger, flight number, date of the journey, and destination details could be entered into an application in the front-end also known as the client. Once the data is entered, the client sends the data to the backend also known as the server, for further processing. The server portion of a client/server application manages the resources shared among multiple users who access the server through multiple clients. The best example to highlight the server part of a client/server program would be a Web server that delivers an HTML page across the Internet to different Web users.

The World Wide Web provides an excellent example of the most basic reason for separating the presentation of data from its storage and processing. On the Web, you do not have control over the platforms and software used by end users to access data. You might consider writing applications for each potential platform you are targeting. The primary selling point of Java as a programming language is the code portability of the programs created in Java. With a code portability that no other language provides, Java allows users to write an application once, distribute it on any client system, and let the client system interpret the program.

This means that you have to write only one version of code that will run on any platform.

Activity : Creating a Server Application

To create a server program using Netbeans IDE, you need to perform the following steps:

Select start->All Programs->NetBeans 5.5.1->NetBeans IDE. The NetBeans IDE 5.5.1 window appears.

Select File->New Project. The New Project window appears.

Ensure that the General option is selected in the Categories section of the ChooseProject page.

Select the Java Application option in the Projects section of the Choose Project page.

Click the Next button. The NameandLocation page is displayed.

Type ServerActivity in the Project Name text box.

Type <Drive Letter>:\JavaProjects in the Project Location text box.

Replace the text, serveractivity.Main to serveractivity.AppServer in the text box given next to the Create Main Class check box.

Click the Finish button. The NetBeans IDE 5.5.1 - ServerActivity window is displayed.

Replace the code in the AppServer.java file with the following code:

Listing 1: Replacing the code in AppServer.java

package serveractivity;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;

class Customer implements Serializable{
	String custName;
	String custPassword;
}

public class AppServer extends Thread{
	ServerSocket serverSocket;
		public AppServer(){
			try{
				ServerSocket = new ServerSocket(1002);
			}catch(IOException e){
				fail(e, “Could not start server.”);
				}

		System.out.println(“Server started . . .”);
			this.start(); // Starts the thread
}
public static void fail(Exception e, String str){
	System.out.println(str +“.” + e);
}

public void run(){
	try{
		while(true){
			Socket client = serverSocket.accept();
			Connection con = new Connection(client);
		}
	}catch(IOException e){
		fail(e, “Notlistening”);
	}
}
public static void main(String[] args) {
	new AppServer();
}
}

class Connection extends Thread{
	protected Socket netClient;
	protected ObjectInputStream fromClient;
	protected PrintStream toClient;
	public Connection(Socket client){
		netClient = client;
			try{
				fromClient = new ObjectInputStream (netClient.getInputStream());
				toClient=new PrintStream(netClient.getOutputStream());
				
				}catch(IOException e){
					try{
						netClient.close();
					}catch(IOException e1){
						System.err.println (“Unable to set up streams” + e1);
						return;
					}
				}
				this.start();
			}
public void run(){
	Customer clientMessage;
	try{
		for(;;)
	{
	clientMessage = (Customer)fromClient.readObject();
	if(clientMessage ==null)
	break;
	// Send acknowledgement to the client 
	toClient.println(“Received from:”+clientMessage.custName);
	//Print the data received from the client to the server console
	System.out.println(“Received from:”+ clientMessage.custName);
	}
	}catch(IOException e){}	
		catch(ClassNotFoundException e1){
			System.out.println(“Error in reading object”+e1);
		}
	finally{
	try{
		netClient.close();
	}catch(IOException e){}
}
}
}

Task 2: Creating a Client Program

To create a client program, you need to perform the following steps:

Right-click the ServerActivity node in the Projects tab, and then select New->File/Folder.

The NewFile dialog box appears.

Select the Java Classes option in the Categories section of the Choose File Type page.

Select the JApplet option in the File Types section of the Choose File Type page. Click the Next button. The NewJApplet dialog box appears.

Replace the text in the Class Name text box with CustomerApplet.

Select the serveractivity option from the Package combo box.

Click the Finish button. The NetBeans IDE 5.5.1 ServerActivity window is displayed.

Ensure that the CustomerApplet.java tab is selected.

Replace the existing code of the CustomerApplet.java file with the following code:

Listing 2: Replacing the existing code of CustomerApplet.java file

package serveractivity;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import javax.swing.*;

class Customer extends Object implements java.io.Serializable{
	String custName;
	String custPassword;
}

public class CustomerApplet extends javax.swing.JApplet {
	JPanel panelObject;
	JLabel labelCustName;
	JLabel labelCustPassword;
	JTextField textCustName;
	JPasswordField textCustPassword;
	JButton buttonLogin;
	GridBagLayout gl;
	GridBagConstraints gbc;
	/** Creates a new instance of
	CustomerApplet */

public void init(){
	//Initialize the layout variables
	gl = new GridBagLayout();
	gbc = new GridBagConstraints();
	panelObject = (JPanel)getContentPane();
	panelObject.setLayout(gl);
	//Initialize controls
	labelCustName = newJLabel(“Customer Login Name”);
	labelCustPassword = new JLabel(“Password”);
	textCustName = new JTextField(15);
	textCustPassword = new JPasswordField(15);
	buttonLogin=new JButton(“Login”);
	//Add controls to the panel
	gbc.anchor =GridBagConstraints.NORTHWEST;
	gbc.gridx = 1;
	gbc.gridy = 5;
	gl.setConstraints(labelCustName,gbc);
	panelObject.add(labelCustName);
	gbc.anchor =GridBagConstraints.NORTHWEST;
	gbc.gridx = 4;
	gbc.gridy = 5;
	gl.setConstraints(textCustName,gbc);
	panelObject.add(textCustName);
	gbc.anchor =GridBagConstraints.NORTHWEST;
	gbc.gridx = 1;
	gbc.gridy = 9;
	gl.setConstraints(labelCustPassword,gbc);
	panelObject.add(labelCustPassword);
	gbc.anchor =GridBagConstraints.NORTHWEST;
	gbc.gridx = 4;
	gbc.gridy = 9;
	gl.setConstraints(textCustPassword,gbc);
	panelObject.add(textCustPassword);
	gbc.anchor=GridBagConstraints.NORTHWEST;
	gbc.gridx=2;
	gbc.gridy=13;
	gl.setConstraints(buttonLogin,gbc);
	panelObject.add(buttonLogin);
	
	LoginActionloginrequest=new LoginAction();
	buttonLogin.addActionListener(loginrequest);
}

class LoginAction implements ActionListener{
	public voidactionPerformed(ActionEvent evt){
		Objectobj=evt.getSource();
			if(obj==buttonLogin){
				// Accepting Customer details
				Customer data=new Customer();
				data.custName =textCustName.getText();
				data.custPassword =new String (textCustPassword.getPassword());
			try{
				// Connecting to the
				ServerSocket toServer;
				toServer = new Socket(“172.23.3.77”,1002);
				ObjectOutputStream streamToServer=new ObjectOutputStream (toServer.getOutputStream());
				// Writing customer details to the server socket
				streamToServer.writeObject((Customer)data);
				BufferedReader fromServer=new BufferedReader ( new InputStreamReader(toServer.getInputStream()));
				// Reading loginstatus from the server socket 
				String status=fromServer.readLine();
				getAppletContext().showStatus(status);
				// Closing the streams
				streamToServer.close();
				fromServer.close();
			}catch(InvalidClassException e){
				getAppletContext().showStatus(“The Customer class is invalid” + e);
			
			}catch(NotSerializableException e){
				getAppletContext().showStatus(“The object is notserializable” + e);
			
			}catch(IOException e){
				getAppletContext().showStatus(“Cannot write tothe server” + e);
			}
		}
	}
}
}

In the preceding code snippet, the IP address passed to the Socket class may change depending on the users machine address.

Task 3: Compiling and Executing the Application

To compile and execute the application using Netbeans IDE, you need to perform the following steps:

  • Right-click the AppServer.java node in the Projects tab, and then select Compile File to compile the file.
  • Right-click the AppServer.java node in the Projects tab, and then select Run File to execute the file.
  • Right-click the CustomerApplet.java node in the Projects tab, and then select Compile File to compile the file.
  • Right-click the CustomerApplet.java node in the Projects tab, and then select Run File to execute the file.
  • Type the customer name in the Customer Login Name text box.
  • Type the password in the Password text box.
  • Click the Login button to establish a connection with the server program, and send and receive the customer details.
  • Repeat the steps 4 to 7 to open multiple clients and establish a connection with the server program.

Conclusion

The client/server model is an application development architecture designed to separate the presentation of data from its internal processing and storage. The client requests for services and the server services these requests. Rules govern the packaging of the data into packets, the speed of transmission, and the reassembling of data to its original form.

These rules are called network protocols. Network protocols are a set of rules and conventions followed by systems that communicate over a network. Some examples of network protocols are TCP/IP, UDP, Apple Talk, and NetBEUI. Java provides a rich library of network-enabled classes that allow applications to readily access network resources. There are two tools available for communication. These are datagrams that use UDP and sockets that use TCP/IP. The Socket class to create a client socket and the ServerSocket class to create a server socket.



Software Developer from India. I hold Master in Computer Applications Degree and is well versed with programming languages such as Java, .Net, C and C++ and possess good working knowledge on Mobile Platforms as well.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login