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 Implement Networking in Java

In this article we will learn about the most important feature of Java that is networking support with an example of connecting client to server and will further add some more features like chatting or file accessing between client and server.

Java provides the programmer with an extensive set of core classes and interfaces to handle a wide range of network protocols. Java has classes that range from low level TCP/IP connections to ones that provide instant access to resources on the World Wide Web. In this article we will see networking concepts and the java.net package through which java supports fundamental networking concepts.

Objective:

  • To understand how java support networking (the way it connect client to server)
  • To create a client and server and connect them using java classes.
  • To add more functionality and implement a chat application.

Common Networking Terms:

A Server is a machine that has some resources that can be shared. For example, a computing server, which provides computing capability; a print server which provides network printing facility, a disk server which provide networked disk space; and web server which stores web pages.

A Client is simply any machine that wants to use the services of a particular server. The server is a permanently available resource, while the client is free to disconnect after its job is done.

The following diagram is a simple illustration of a server serving multiple clients:

shows Client server communication.

Figure 1: shows Client server communication.

Sockets:

Java programs communicate through programming abstraction called a socket. A socket represents the endpoint of a network communication. Sockets provide a simple read/write interface and hide the implementation details network and transport layer protocols. It is used to indicate one of the client wishes to make connection to a server, it will create a socket at its end of the communication link.

Ports:

A port number identifies a specific application running in the machine. A port is a number in the range 165535. It is a transport layer address used by TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) to handle communication between applications. For example, an email application on one machine wants to communicate with an email application on another machine. The machines are identified by the IP address but the email applications are identified by the port number at which they communicate i.e. Port 25.

The JAVA.NET Package

The java.net package provides classes and interfaces for implementing network applications such as sockets, network address, Uniform Resource Locators (URLs) etc.

Java.net package contains many classes and interface but for this article will cover only those which will use in our application.

ServerSocket Class

The ServerSocket class is used to create a server that listens for incoming connections from one or more clients. A Server socket binds itself to a specific port so that clients can connect to it.

Constructors

Constructors Description
ServerSocket(int port) Binds the Server socket to the specified port number. If 0 is passed, any free port will be used. However , clients will be unable to access the service unless notified the port number.
ServerSocket(int port, int numberOfClients) Binds the server socket to the specified port number and allocates sufficient spaces to the queue to support the specified number of client sockets.
ServerSocket(int port, int numberOfClients, InetAddress address) Binds the server socket to the specified port number, and allocates sufficient space to the queue to support the specified number of client socket and the IP address to which this socket binds.

Important Methods

Methods Description
accept() Listens for socket connection. This is a blocking I/O operation, and will not return until a connection is made. When a connection is established, a Socket object will be returned.
bind() Binds connection to destination.
close() Closes connection.
getChannel() Returns channel for connection.
getInetAddress() Returns address of connection.
getLocalPort() Returns local port used for connection.
getLocalSocketAddress() Returns local socket information.
isBound() Checks whether socket is bound.
isClosed() Checks whether socket is closed.
toString() Converts server socket into string.

Socket Class

The Socket class represents a TCP client socket, which connects to a server socket and infinite protocol exchanges.

Constructors

Constructors Description
Socket(InetAddress address,int port) Creates a socket connected to the specified IP address and port. Can throw an IOException.
Socket(String host,int port) Creates a socket connected to the specified host and port. Can throw an UnknownHostException or an IOException.

Important Methods

Methods Description
bind() Binds connection to destination.
close() Closes connection.
connect() Makes connection to destination.
getChannel() Returns channel for connection.
getInetAddress() Returns address associated with the Socket object.
getInputStream() Returns input stream for connection.
getLocalSocketAddress() Returns local socket information.
isBound() Checks whether socket is bound.
isClosed() Checks whether socket is closed.

Creating TCP Client and Server

In this section, we will see how to create a server socket and client socket.

How to create a server socket

To create a server socket, follow the following steps:

  1. Create a ServerSocket object which listens to a specific port.
  2. Call the accept() method which accepts client requests. This method returns the client Socket object.
  3. Use the Socket object to communicate with the client.

Listing 1: Creating a server socket:

import java.net.*;
import java.io.*;

public class Server {
	
	public static void main(String args[]) throws UnknownHostException,IOException
	{
		int port=4455;
		ServerSocket ss=new ServerSocket(port);
		Socket s=ss.accept();// wait for client
		while(!done)
		{
			//Communication with client
		}
		ss.close();
	}

}

How to create a client socket

To create a client socket, follow the following steps:

  1. Create an object of the Socket class using the server name and port as parameters.
  2. Communicate with the server.
  3. Close the socket.

Lising2: Creating a client socket

import java.net.*;
import java.io.*;

public class Client {

	public static void main(String args[]) throws UnknownHostException,IOException
	{
		int port=4455;
		String servername="server";
		Socket ss=new Socket(servername,port);
		while(!done)
		{
			//Communication with Server
		}
		ss.close();
	}
	
}

Complete Example for Chat application using Networking in java:

In this example will develop and application for two way chatting between client and server till any one of them types the message “END”. Follow these simple steps to create a chat application:

Listing3: Create Server Class with following code:

import java.net.*;
import java.io.*;

class Server
{
	public static void main(String args[]) throws UnknownHostException,IOException
	{
		ServerSocket ss=new ServerSocket(4455);
		System.out.println("Server Started.........");

		Socket s=ss.accept();
		System.out.println("Client Connected.......");

		InputStream is=s.getInputStream();
		OutputStream os=s.getOutputStream();

		DataInputStream dis=new DataInputStream(is);
		DataOutputStream dos=new DataOutputStream(os);
		
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		
		String str="";
		String str1="";
		while(true)
		{
			str=dis.readUTF();
			System.out.println(str);
			str1=br.readLine();
			dos.writeUTF(str1);
			if(str.equals("END")||str.equals("end"))
			{
				System.out.println("Bye!...Client requested To quit");
				System.exit(0);
			
			}
		}

	}
}

Listing4: Next create a Client class with following code:

import java.net.*;
import java.io.*;

class Client
{
	public static void main(String args[]) throws UnknownHostException,IOException
	{
		Socket s=new Socket("localhost",4455);
		
		InputStream is=s.getInputStream();
		OutputStream os=s.getOutputStream();

		DataInputStream dis=new DataInputStream(is);
		DataOutputStream dos=new DataOutputStream(os);

		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		
		String str="";
		String str1="";
		while(true)
		{
			str=br.readLine();
			dos.writeUTF(str);
			
			str1=dis.readUTF();
			System.out.println(str1);
			
			if(str.equals("END")||str.equals("end"))
			{
				System.out.println("Bye!...Server quit");
				System.exit(0);
			
			}

		}
	}
}

Now run the Server.java first you will see the following output:

Shows the output after running Server.java with message on console that sever started

Figure 2: Shows the output after running Server.java with message on console that sever started

Then run the Client.java you will see the following output:

Shows the output after running Client.java with message on server console that client connected

Figure 3: Shows the output after running Client.java with message on server console that client connected

Now client is properly connected and we can chat between client and server easily. See the figure below:

Shows the chatting between Client console and Server console.

Figure 4: Shows the chatting between Client console and Server console.

Now when we type end it will end the chat between client and server. See the figure below:

Shows when we type end on console. It will terminate the client and server and end the chat.

Figure 5: Shows when we type end on console. It will terminate the client and server and end the chat.

Conclusion:

In this article we learned following things:

  1. Networking concept in java.
  2. Some networking supported classes with their constructors and important methods.
  3. Lastly a chatting application between client and server.


I am a software developer from India with hands on experience on java, html for over 5 years.

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