Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Advanced Programming Chapter 5 Java Networking

Chapter 5 discusses Java Networking, which involves connecting multiple computing devices to share resources using the Java programming language. It covers key concepts such as IP addresses, protocols, and socket programming, detailing both connection-oriented (TCP) and connection-less (UDP) methods. The chapter also provides practical examples of client-server communication using Java's socket classes and demonstrates how to retrieve IP addresses using the InetAddress class.

Uploaded by

shalomsolomon977
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Advanced Programming Chapter 5 Java Networking

Chapter 5 discusses Java Networking, which involves connecting multiple computing devices to share resources using the Java programming language. It covers key concepts such as IP addresses, protocols, and socket programming, detailing both connection-oriented (TCP) and connection-less (UDP) methods. The chapter also provides practical examples of client-server communication using Java's socket classes and demonstrates how to retrieve IP addresses using the InetAddress class.

Uploaded by

shalomsolomon977
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Chapter 5: Java Networking

What is Java Networking


When computing devices such as laptops, desktops, servers, smartphones, and tablets and an
eternally-expanding arrangement of IoT gadgets/devices such as cameras, door locks, doorbells,
refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and
data with each other is known as networking.

In simple words, the term network programming is writing programs that can be executed over
various computing devices, in which all the devices are connected to each other to share resources
using a network. Here, we are going to discuss Java Networking.

Java is the leading programming language composed from scratch with network programming.
Java Networking is a notion of combining two or more computing devices together to share
resources.

Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.

Advantage of Java Networking

1. Sharing resources
2. Centralize software management

The java.net package of the Java programming language includes various classes that provide an
easy-to-use means to access network resources. For example Socket, ServerSocket,
DatagramSocket , DatagramPacket, InetAddress etc.

The java.net package also provides two well-known network protocols. These are

1. Transmission Control Protocol (TCP): provides reliable communication between the


sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2. User Datagram Protocol (UDP): provides a connection-less protocol service by allowing
packet of data to be transferred along two or more nodes

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 1


Java Networking Terminology

The widely used Java networking terminologies are given below:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1

It is a logical address that can be changed.

2) Protocol

A network protocol is an organized set of commands that define how data is transmitted between
different devices in the same network. Network protocols are the reason through which a user can
easily communicate with people all over the world and thus play a critical role in modern digital
communications. For Example – TCP, FTP, Telnet, etc.

3) Port Number

The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.

The port number is associated with the IP address for communication between two applications.

4) MAC Address

MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller).
A network node can have multiple NIC but each with unique MAC address.

For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 2


5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So, it is reliable but


slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So, it is not reliable
but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is one endpoint of a two-way communication connection between the two applications
running on the network. The socket mechanism presents a method of inter-process communication
(IPC) by setting named contact points between which the communication occurs.

Java Socket Programming

Java Socket programming is used for communication between the applications running on
different JRE. Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 3


Socket Programming steps:

The following are the steps that occur on establishing a TCP connection between two computers
using socket programming:

Step 1: The server instantiates a ServerSocket object, indicating at which port number
communication will occur.
Step 2: After instantiating the ServerSocket object, the server requests the accept() method of the
ServerSocket class. This program pauses until a client connects to the server on the given port.
Step 3: After the server is idling, a client instantiates an object of Socket class, defining the server
name and the port number to connect to the server.
Step 4: After the above step, the constructor of the Socket class strives to connect the client to the
designated server and the port number. If communication is authenticated, the client forthwith has
a Socket object proficient in interacting with the server.
Step 5: On the server-side, the accept() method returns a reference to a new socket on the server
connected to the client’s socket.

After the connections are stabilized, communication can happen using I/O streams. Each object of
a socket class has both an OutputStream and an InputStream. The client’s OutputStream is
correlated to the server’s InputStream, and the client’s InputStream is combined with the server’s
OutputStream. Transmission Control Protocol (TCP) is a two-way communication protocol.

Connection-oriented Socket Programming

Socket class

A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.

ServerSocket class

The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 4


Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we are
using 5000 port number for the communication between the client and server. You may also choose
any other port number. The accept() method waits for the client. If clients connect with the given
port number, it returns an instance of Socket.

ServerSocket ss=new ServerSocket(5000);


Socket s=ss.accept(); //establishes connection and waits for the client

Creating Client:

To create the client application, we need to create the instance of Socket class. Here, we need to
pass the IP address or hostname of the Server and a port number. Here, we are using "localhost"
because our server is running on same system.

Socket s=new Socket("localhost",5000);

Let's see a simple of Java socket programming example where client sends a text and server
receives and prints it. First create Java Project called Java_Networking_Project and create all the
classes discussed below under this project.

Client-Write and Server Read (one side)


File: TCP_Server_Machine1.java
import java.io.*;
import java.net.*;
public class TCP_Server_Machine1 {
public static void main(String[] args){
try{ ServerSocket ss=new ServerSocket(5000);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 5


}catch(Exception e)
{ System.out.println(e);
}
}
}

File: TCP_Client_Machine1.java

import java.io.*;
import java.net.*;
public class TCP_Client_Machine1 {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",5000);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

Run TCP_Server_Machine1.java first and then TCP_Client_Machine1.java. After running the


client application, a message will be displayed on the server console.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 6


Server and client Read-Write both side:

In this example, client will write first to the server then server will receive and print the text. Then
server will write to the client and client will receive and print the text. The step goes on.

File:TCP_Server_Machine2.java

import java.net.*;
import java.io.*;
class TCP_Server_Machine2{
public static void main(String args[])throws Exception{
try{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 7


File: TCP_Client_Machine2.java

import java.net.*;
import java.io.*;
class TCP_Client_Machine2{
public static void main(String args[])throws Exception{
try{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}

dout.close();
s.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

Run TCP_Server_Machine2.java and then TCP_Client_Machine2.java. Client machine write text


for the server and the message will be displayed on the server console. Then the server respond
message to client, a message will be displayed on the client console.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 8


Connection-less Socket Programming:

Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP (User Datagram Protocol) instead of TCP(Transmission Control
Protocol).

Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets.

Java DatagramPacket is a message that can be sent or received. It is a data container. If you send
multiple packets, it may arrive in any order.

Datagrams are collection of information sent from one device to another device via the established
network. When the datagram is sent to the targeted device, there is no assurance that it will reach
to the target device safely and completely. The UDP protocol is used to implement the datagrams
in Java.

Sending DatagramPacket by DatagramSocket


//UDP_Sender.java
import java.net.*;
public class UDP_Sender{
public static void main(String[] args) throws Exception {
try{
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 9


Receiving DatagramPacket by DatagramSocket

//UDP_Receiver.java
import java.net.*;
public class UDP_Receiver{
public static void main(String[] args) throws Exception {
try{ DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}catch(Exception e)
{
System.out.println(e);
}

}
}
Run UDP_Sender.java, run UDP_Receiver and again run UDP_Sender.java the message Welcome
java is displayed on UDP_Receiver console which is transferred from UDP_Sender

Java InetAddress class

The java.net.InetAddress class provides methods to get the IP of any host name for
example www.javatpoint.com, www.google.com, www.facebook.com, etc.

An instance of InetAddress represents the IP address with its corresponding host name. An IP
address helps to identify a specific resource on the network using a numerical representation.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 10


Let's see a simple example of InetAddress class to get IP address of www.javatpoint.com and
www.google.com website, and IP address, Host Name and MAC address of your machine.

//InetAddressDemo.java

import java.io.*;
import java.net.*;
public class InetAddressDemo{
public static void main(String[] args){
try{
InetAddress ip1=InetAddress.getByName("www.javatpoint.com");
InetAddress ip2=InetAddress.getByName("www.google.com");
System.out.println("Javatpoint Host Name: "+ip1.getHostName());
System.out.println("Javatpoint IP Address: "+ip1.getHostAddress());
System.out.println("Google Host Name: "+ip2.getHostName());
System.out.println("Google IP Address: "+ip2.getHostAddress());

System.out.println("Your Machine Host Name, IP Address and MAC Address are : ");
String ipAddress_localmachine="", macAddress_localmachine="",hostname_localmachine="";
int i=0;
StringBuilder sb = new StringBuilder();
InetAddress inetAddress_localmachine =InetAddress.getLocalHost();
ipAddress_localmachine =inetAddress_localmachine.getHostAddress();
hostname_localmachine =inetAddress_localmachine.getHostName();
NetworkInterface network=NetworkInterface.getByInetAddress(inetAddress_localmachine);
byte[] hw=network.getHardwareAddress();
for(i=0; i<hw.length; i++)
sb.append(String.format("%02X%s", hw[i], (i < hw.length - 1) ? "-" :""));
macAddress_localmachine=sb.toString();

System.out.println("Your Machine Host Name: "+hostname_localmachine);


System.out.println("Your Machine IP Address: "+ ipAddress_localmachine);
System.out.println("Your Machine MAC Address: "+macAddress_localmachine);

}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Connect your computer to internet and run the file and see the output. In my laptop I get the
information. When you run the file you may get the same Host Name and IP Address for
www.javatpoint.com and www.google.com because you may access the same server address of each
site, but you pc or laptop Machine Name, IP Address and MAC Address must be different from
the output shown below.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 11


COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 12

You might also like