Chapter 05
Chapter 05
Chapter 5
Networking in Java
1
Objectives
Learn about Networking in java
provides networking overview
provides types of connections
2
Networking in java
Java Networking is a concept of connecting two or more computing devices together
so that we can share resources.
Networking in Java involves the ability to communicate and exchange data between
different devices over a network
Each machine on a network is called a node
Every network node has an address, a sequence of bytes that uniquely identifies it (IP
address).
The more bytes there are in each address, the more addresses there are available and
the more devices that can be connected to the network simultaneously.
Addresses are assigned differently on different kinds of networks. Ethernet addresses
are attached to the physical Ethernet hardware(MAC address).
On some kinds of networks, nodes also have text names that help human beings
identify them such as “www.elharo.com” or “Beth Harold’s Computer.” refers to
exactly one address.
All modern computer networks are packet-switched networks: data traveling on the
network is broken into chunks called packets and each packet is handled separately.
Each packet contains information about who sent it and where it’s going.
3
Types of connections
Protocols
Define the rules that govern the communications between two computers connected to
the network.
Roles: addressing and routing of messages, error detection and recovery, sequence
of the messages exchanged, and the semantic, which specifies the action taken by
each entity when specific events occur.
Example: HTTP protocol for communication between web browsers and servers.
Protocols are designed based on a layered architecture such as the OSI reference
model
(Home reading OSI && TCP/IP Model).
There are two different approaches to communication protocols
Connectionless and
Connection-oriented
They define how data is transmitted and delivered between devices in a network.
4
Cont.
Connectionless Protocol:
A connectionless protocol, such as User Datagram Protocol (UDP), does not
transmission.
Some key characteristics of connectionless protocols are:
No Connection Setup: There is no initial handshake or connection establishment process between
the sender and receiver.
Unreliable Delivery: Connectionless protocols do not guarantee reliable delivery of data. Packets
may be lost, duplicated, or arrive out of order.
Low Overhead: Connectionless protocols have lower overhead compared to connection-oriented
protocols since they do not require maintaining connection state information.
Connectionless protocols are often used in scenarios where real-time communication,
low latency, or simplicity is more important than guaranteed delivery,
such as video streaming, voice over IP (VoIP), online gaming, or situations where a
small amount of data needs to be sent quickly.
5
Cont.
Connection-Oriented Protocol:
A connection-oriented protocol, such as Transmission Control Protocol (TCP),
7
java socket programming
Java socket programming provides facility to share data between different
computing devices.
Java Program communicates over the network at the application layer.
java.net package is useful for all the Java networking classes and interfaces.
java.net package encapsulate large number of classes and interface that
provides an easy-to use means to access network resources.
Here are some important classes and interfaces of java.net package.
CLASSES INTERFACES
CacheRequest Datagrampacket InetAddress SocketOption
CookieManager ServerSocket CookieStore ProtocolFamily
Inet Address DatagramSocket FileNameMap ServerSocket
Socket URLConnection SocketImplFactory CookiePolicy
8
Cont.
The java.net package in Java supports multiple protocols for networking.
The two most commonly used protocols supported by the java.net package are:
Transmission Control Protocol(TCP)
It provides reliable communication between the sender and receiver.
TCP is used along with the Internet Protocol referred as TCP/IP.
User Datagram Protocol (UDP)
It provides a connection-less protocol service by allowing packet of data to be
transferred along two or more nodes.
Advantage of Java Networking
Sharing resources
Centralize software management
9
Networking Terminologies in Java
i. IP Address
The IP address is a unique number assigned to a node of a network e.g.
192.168.0.1.
It is composed of octets that range from 0 to 255.
It is a logical address that can be changed.
ii. Protocol
A protocol is an organized set of rules that determine how data is transmitted
between devices on the same network.
For example: TCP, FTP, Telnet, SMTP, POP etc.
iii. Port Number
The port number uniquely identifies a particular application (process) or service
on a system.
It is a 16-bit unsigned integer, ranging from 0 to 65535.
Well-known Ports (0-1023): Well-known ports are assigned to specific services or applications
(Process) by the Internet Assigned Numbers Authority (IANA).
For example, port 80 is used for HTTP (web), port 443 is used for HTTPS (secure web), port 25 is
used for SMTP (email), and so on. These ports are commonly used by widely recognized services. 10
Cont.
Registered Ports (1024-49151): Registered ports are assigned by IANA to specific applications or services
that are not considered well-known.
These ports can be used by applications and services that are not part of the operating system or commonly
recognized protocols.
Dynamic or Private Ports (49152-65535): Dynamic or private ports are available for use by applications or
services dynamically or on a private basis.
These ports are typically used for temporary connections or by client applications when connecting to
servers.
IV. Socket
A socket is a software endpoint that enables communication between two devices
over a network.
it used to identify both a machine and a service within the machine.
A socket represents one endpoint of a network connection, and it is identified by an
IP address and a port number.
Sockets are used in network programming to establish connections and transfer data
between client and server applications.
A socket represents one endpoint of a network connection and can read and write
data.
In programming, sockets provide an interface to send and receive data using 11
Cont.
Summary,
IP addresses identify devices on a network, sockets represent the endpoints for
source and destination of data packets and allowing multiple applications to coexist on
a single device.
Feature IP address Socket Port number
Identifies a Identifies a specific
Identifies a device on a
Purpose communication endpoint application or service on a
network
between two applications device
12
Java Socket Programming (Cont.)
● It is used for communication between the applications running on different JRE.
● It can be connection-oriented or connection-less.
● Socket basically provides a communication mechanism between two computers
using TCP.
● In Socket Programming, Socket and ServerSocket classes are used for
connection-oriented, and DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
● ServerSocket class is for servers and Socket class is for the client.
● The client in socket programming must know two information
1. IP Address of Server, and
2. Port number.
A. Socket class
● A socket is simply an endpoint for communications between the machines.
● The Socket class can be used to create a socket.
13
Cont.
Socket class methods
Method Description
public InputStream returns the InputStream attached with this socket.
getInputStream()
Public OutputStream returns the OutputStream attached with this socket.
getOutputStream()
public synchronized void closes this socket
close()
B. ServerSocket class
● The ServerSocket class can be used to create a server socket. This object is used
to establish communication with the clients.
Method Description
1) public Socket accept() returns the socket and establish a connection between
server and client.
2) public synchronized void closes the server socket. 14
Establishing a TCP connection between two computing devices 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 invokes the accept() method of the
ServerSocket class.
● This program waits until a client connects to the server on the given port.
Step 3 –
After the server is waiting, a client instantiates an object of Socket class, defining the server name
and the port number to connect to.
Step 4 –
After the above step, the constructor of the Socket class tries 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.
15
Establishing a simple server using stream
sockets
Establishing a simple server in Java requires five steps.
Step 1
● is to create a ServerSocket object. A call to the ServerSocket constructor, such as
ServerSocket ss = new ServerSocket(portNumber);
Step 2
● The server listens indefinitely(or blocks) for an attempt by a client to connect.
● To listen for a client connection, the program calls ServerSocket accept() method as,
Socket s=ss.accept();
which returns a Socket when a connection with a client is established.
● The Socket allows the server to interact with the client.
Step 3
● is to get the OutputStream and InputStream objects that enable the server to
communicate with the client by sending and receiving bytes.
● The server sends information to the client via an OutputStream and receives
information from the client via an InputStream.
16
Cont.
Step 4
● is the Processing phase, in which the server and the client communicate via the
OutputStream and InputStream objects.
Step 5
● When the transmission is complete, the server closes the connection by invoking the
close() method on the streams and on the Socket.
Example of Java Socket Programming
A. Creating Server
● To create the server application, we need to create the instance of
ServerSocket class.
● Here, we are using 6666 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 connects with the given
port number, it returns an instance of Socket.
17
Cont.
ServerSocket ss=new ServerSocket(6666);
//establishes connection and waits for the client
Socket s=ss.accept();
// MyServer.java
System.out.println("message= "+str);
import java.io.*; ss.close();
import java.net.*; }catch(Exception e){
public class MyServer{ System.out.println(e);
public static void main(String[] args) }
{ }
try{ }
String str=(String)dis.readUTF(); 18
Establishing a simple client using stream
sockets
Establishing a simple client in Java requires four steps.
Step 1
● we create a Socket object to connect to the server.
● The Socket constructor establishes the connection to the server.
● For example, the statement
Socket s = new Socket(serverAddress, port);
Step 2
The client uses Socket methods getInputStream and getOutputStream to obtain
references to the Socket's InputStream and OutputStream.
Step 3
It is the processing phase in which the client and the server communicate via
the InputStream and OutputStream objects.
Step 4
• The client closes the connection when the transmission is complete by invoking
the close() method on the streams and on the Socket.
19
Cont.
B. 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.
22
Example
simple client-server communication where the client sends a message to the server,
and the server echoes the message back to the client
// Server Code
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) {
try {
// Create a server socket on port 12345
ServerSocket serverSocket = new ServerSocket(12345);
26
UDP Example
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
try {
// Create a server socket on port 12345
DatagramSocket serverSocket = new DatagramSocket(12345);
System.out.println("Server started. Waiting for client message...");
// Create a byte array to receive client data
byte[] receiveData = new byte[1024];
// Create a DatagramPacket to hold the received data
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
// Receive data from the client
serverSocket.receive(receivePacket);
27
Cont.
// Convert the received data to a string
String clientMessage = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Received from client: " + clientMessage);
System.out.println("Server closed.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
28
Cont.
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
try {
// Create a client socket
DatagramSocket clientSocket = new DatagramSocket();
29
Cont.
// Send the packet to the server
clientSocket.send(sendPacket);
System.out.println("Sent to server: " + message);
// Close the client sock
// Create a byte array to receive the server's clientSocket.close(
response } catch (Exception e) {
byte[] receiveData = new byte[1024]; e.printStackTrace()
}
// Create a DatagramPacket to hold the received }
data }
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
31
Cont.
Marshalling and Unmarshalling: RMI transparently handles the marshalling
(serialization) and unmarshalling (deserialization) of method arguments and return
values. The parameters and results are automatically serialized and transmitted
between the client and server JVMs.
Stub and Skeleton: RMI uses stubs and skeletons to facilitate remote method
invocations. The stub on the client side acts as a local representative of the remote
object and forwards method invocations to the server-side skeleton, which in turn
invokes the actual object's methods.
Registry: RMI uses a registry service to locate remote objects. The registry acts as a
central lookup service where clients can find the remote objects they need to
communicate with.
Security: RMI provides mechanisms for securing remote communication, such as
authentication and encryption, to ensure the integrity and confidentiality of data
transmitted between client and server.
32
RMI system
33
Steps :RMI execution
The client uses the client-side stub to make a request of the remote object.
The server object receives this request from a server-side object skeleton.
A client initiates an RMI invocation by calling a method on a stub object.
The stub maintains an internal reference to the remote object it represents and
forwards the method invocation request through the remote reference layer by
marshaling the method arguments into serialized form and asking the remote
reference layer to forward the method request and arguments to the appropriate
remote object.
Marshaling involves converting local objects into portable form so that they can be
transmitted to a remote process.
Each object (e.g. a String object, an array object, or a user defined object) is checked
as it is marshaled, to determine whether it implements the java.rmi.Remote interface.
If it does, its remote reference is used as its marshaled data. If it isn’t a Remote object
but is rather a Serializable object, the object is serialized into bytes that are sent to the
remote host and reconstructed into a copy of the local object.
If the object is neither Remote nor Serializable, the stub throws a
java.rmi.MarshalException back to the client.
34
Cont.
If the marshaling of method arguments succeeds, the client-side remote reference
layer receives the remote reference and marshaled arguments from the stub.
The remote reference layer converts the client request into low-level RMI transport
requests,
i.e., into a single network-level request and sends it over the wire to the sole remote object (since in
Java 2 the communication style supported is the point-to-point object references) that corresponds
to the remote reference passed along with the request.
On the server, the server-side remote reference layer receives the transport-level
request and converts it into a request for the server skeleton that matches the
referenced object.
The skeleton converts the remote request into the appropriate method call on the
actual server object. This involves unmarshaling the method arguments into the server
environment and passing them to the server object.
Arguments sent as remote references are converted into local stubs on the server, and
arguments sent as serialized objects are converted into local copies of the originals.
35
Cont.
If the method calls generates a return value or an exception, the skeleton marshals
the object for transport back to the client and forwards it through the server reference
layer.
The result is sent back using the appropriate transport protocol (e.g. Socket API using
TCP/IP), where it passes through the client reference layer and stub, is unmarshaled by
the stub, and is finally handed back to the client thread that invoked the remote
method.
RMI programming
36
Cont.
Step 1: Write a java program to create an interface named adder.
package addrmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface adder extends Remote{
public void add(double a,double b)throws
RemoteException;
}
Step 2: Write a program to implement previously created interface
package addrmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class AddRmi extends
UnicastRemoteObject implements adder{
public AddRmi()throws
RemoteException {
}
@Override
public void add(double a,double b){
System.out.println(a+b); 37
Cont.
Step 3: Write a server program
package addrmi; }
import java.rmi.RemoteException; }
import java.rmi.registry.Registry; public static void main(String args[
import java.rmi.registry.LocateRegistry; {
public class AddServer { AddServer a = new AddServer();
public void Test1(){ a.Test1();
try{ }
//create port number }
Registry r =
LocateRegistry.createRegistry(2000);
//give the service name AddService and
implement it with the implementation class
r.rebind("AddService" , new
AddRmi());
System.out.println("server is ready
to accept requests please run your client
program");
}catch(RemoteException ex){
System.out.println("not
38
connected " + ex)
Cont.
Step 4: Write a client program
public static void main(String args[]) throws
package addrmi; NotBoundException{
import java.rmi.NotBoundException; AddClient add= new AddClient();
import java.rmi.RemoteException; add.client1();
import java.rmi.registry.LocateRegistry; }
import java.rmi.registry.Registry; }
public class AddClient { Now, run the server first then the client
public void client1() throws
NotBoundException{
try{
Registry
r=LocateRegistry.getRegistry("localhost",
2000);
adder a = (adder)
r.lookup("AddService");
a.add(23, 67);
System.out.println("numbers sent
to the server to get add service");
}catch(RemoteException ex){
ex.printStackTrace(); 39