[Go to site: main page, start]

0% found this document useful (0 votes)
29 views12 pages

Java Networking and Socket Programming

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views12 pages

Java Networking and Socket Programming

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 [Link] 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 [Link] 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. [Link]

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=[Link](); //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 [Link].*;
import [Link].*;
public class TCP_Server_Machine1 {
public static void main(String[] args){
try{ ServerSocket ss=new ServerSocket(5000);
Socket s=[Link]();//establishes connection
DataInputStream dis=new DataInputStream([Link]());
String str=(String)[Link]();
[Link]("message= "+str);
[Link]();

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 5


}catch(Exception e)
{ [Link](e);
}
}
}

File: TCP_Client_Machine1.java

import [Link].*;
import [Link].*;
public class TCP_Client_Machine1 {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",5000);
DataOutputStream dout=new DataOutputStream([Link]());
[Link]("Hello Server");
[Link]();
[Link]();
[Link]();
}catch(Exception e)
{
[Link](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 [Link].*;
import [Link].*;
class TCP_Server_Machine2{
public static void main(String args[])throws Exception{
try{
ServerSocket ss=new ServerSocket(3333);
Socket s=[Link]();
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(![Link]("stop")){
str=[Link]();
[Link]("client says: "+str);
str2=[Link]();
[Link](str2);
[Link]();
}
[Link]();
[Link]();
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 7


File: TCP_Client_Machine2.java

import [Link].*;
import [Link].*;
class TCP_Client_Machine2{
public static void main(String args[])throws Exception{
try{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(![Link]("stop")){
str=[Link]();
[Link](str);
[Link]();
str2=[Link]();
[Link]("Server says: "+str2);
}

[Link]();
[Link]();
}catch(Exception e)
{
[Link](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 [Link].*;
public class UDP_Sender{
public static void main(String[] args) throws Exception {
try{
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = [Link]("[Link]");
DatagramPacket dp = new DatagramPacket([Link](), [Link](), ip, 3000);
[Link](dp);
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 9


Receiving DatagramPacket by DatagramSocket

//UDP_Receiver.java
import [Link].*;
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);
[Link](dp);
String str = new String([Link](), 0, [Link]());
[Link](str);
[Link]();
}catch(Exception e)
{
[Link](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 [Link] class provides methods to get the IP of any host name for
example [Link], [Link], [Link], 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 [Link] and
[Link] website, and IP address, Host Name and MAC address of your machine.

//[Link]

import [Link].*;
import [Link].*;
public class InetAddressDemo{
public static void main(String[] args){
try{
InetAddress ip1=[Link]("[Link]");
InetAddress ip2=[Link]("[Link]");
[Link]("Javatpoint Host Name: "+[Link]());
[Link]("Javatpoint IP Address: "+[Link]());
[Link]("Google Host Name: "+[Link]());
[Link]("Google IP Address: "+[Link]());

[Link]("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 =[Link]();
ipAddress_localmachine =inetAddress_localmachine.getHostAddress();
hostname_localmachine =inetAddress_localmachine.getHostName();
NetworkInterface network=[Link](inetAddress_localmachine);
byte[] hw=[Link]();
for(i=0; i<[Link]; i++)
[Link]([Link]("%02X%s", hw[i], (i < [Link] - 1) ? "-" :""));
macAddress_localmachine=[Link]();

[Link]("Your Machine Host Name: "+hostname_localmachine);


[Link]("Your Machine IP Address: "+ ipAddress_localmachine);
[Link]("Your Machine MAC Address: "+macAddress_localmachine);

}catch(Exception e)
{
[Link]([Link]());
}
}
}
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
[Link] and [Link] 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

Common questions

Powered by AI

In Java networking, connection-oriented protocols, exemplified by TCP, ensure reliable communication with data retransmission and out-of-order data handling. Implemented with ServerSocket and Socket classes, TCP provides a persistent connection for applications like web browsing and email. Conversely, connectionless protocols like UDP, which use DatagramSocket and DatagramPacket classes, offer faster transmission without guarantee of arrival, suitable for applications where speed supersedes reliability, such as gaming or live broadcasts. Both serve distinct needs, balancing reliability and efficiency .

The java.net package simplifies network resource access in Java by providing classes like Socket, ServerSocket, DatagramSocket, and InetAddress, which abstract complex network interactions. For instance, Socket and ServerSocket enable easy establishment of a client-server connection, whereas DatagramSocket supports connection-less communication with minimal overhead. InetAddress can resolve hostnames into IPs, streamlining interactions across nodes. This abstraction allows developers to focus on application logic without managing intricate network details .

The primary advantages of Java networking are the ability to share resources and centralized software management. These advantages manifest in network programming by allowing devices connected in a network to access shared resources such as files or devices or centrally managed software systems with ease, thus facilitating efficient data management and resource allocation .

Port numbers are critical in Java networking as they uniquely identify different applications on a device. By associating a specific IP address with a port number, network communications can be directed to the correct application endpoint; thus, they facilitate the proper routing of data packets to the respective application engaged in a network session .

TCP (Transmission Control Protocol) is connection-oriented and reliable, as it ensures data transmission acknowledgment between sender and receiver, making it suitable for applications requiring accurate data delivery, such as file transfers. UDP (User Datagram Protocol) is connection-less, does not guarantee delivery acknowledgment, and is faster but less reliable, making it ideal for applications where speed is crucial and error correction can be managed at the application level, like streaming services .

Java supports key network protocols such as TCP/IP and UDP. TCP/IP, being connection-oriented and reliable, is used in scenarios where data integrity and order are critical, such as web server communication, database sharing, and file transfers. UDP, on the other hand, being connection-less and offering lower overhead, suits applications where speed is more crucial than perfect data transmission, like live video streaming or online gaming. This allows Java developers to choose the appropriate protocol based on their specific use case requirements for network programming .

In Java socket programming, DatagramSocket is used to create a connectionless socket for sending and receiving packets, while DatagramPacket acts as a container for data in transit. In a UDP communication scenario, DatagramSocket sends or receives DatagramPackets, which encapsulate the data being transmitted over the network. Since UDP does not establish a direct connection, packets may arrive in any order, and DatagramSocket handles these datagrams without guaranteeing reliable delivery .

Java's DatagramPacket class facilitates data transmission in a connection-less environment by encapsulating the data and its destination information, allowing DatagramSocket to send it across the network. However, it lacks delivery assurance, making it unreliable for applications demanding guaranteed data receipt. This limitation is a trade-off for reduced communication latency, which is often acceptable in applications where speed is prioritized, like DNS lookups or VoIP .

The InetAddress class in Java networking is responsible for finding the IP address of a host or resolving a hostname to its IP address. This functionality is important for network communication as it enables programs to identify resources on a network using IP addresses or hostnames, thereby facilitating interactions across different networked environments. It also provides information on the local machine's network configuration, including host name, IP address, and MAC address .

Socket programming in Java facilitates communication between applications by providing a mechanism for inter-process communication. The steps involved in establishing a TCP connection using socket programming include: 1) The server instantiates a ServerSocket object with a designated port, 2) Calls the accept() method which waits for a client's connection, 3) A client creates a Socket object specifying the server's name and port, 4) Upon successful connection, the server's accept() returns a new Socket object linked to the client, thus allowing data exchange through InputStream and OutputStream on both sides .

You might also like