0% found this document useful (0 votes)
9 views

Chapter 05

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Chapter 05

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Java Programming (COSC -3053)

Chapter 5
Networking in Java

1
Objectives
 Learn about Networking in java
 provides networking overview

provides types of connections

 Understand Socket Programming:


 Socket, port and URI
 Implementing Socket programming
 Remote method invocation (RMI)
 Overview of RMI
 The RMI registry
 The remote Interface
 Implementing RMI

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

and flow controls etc.


 A protocol specification consists of the syntax, which defines the kinds and formats

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

establish a dedicated connection before transmitting data.


 Each packet of data, known as a datagram, is treated independently and is routed

individually from the source to the destination.


 The packets can take different paths and may arrive out of order or be lost during

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),

establishes a dedicated connection between the sender and receiver before


transmitting data.
 This connection is established through a three-way handshake process, which involves

exchanging control messages to ensure both parties are ready to communicate.


 Some key characteristics of connection-oriented protocols are:

Connection Setup: Connection-oriented protocols require an initial setup phase, including a
handshake process, to establish a reliable connection between the sender and receiver.

Reliable Delivery: Connection-oriented protocols provide reliable delivery of data. They ensure
that packets are delivered in the correct order, without loss or duplication.

Higher Overhead: Connection-oriented protocols have higher overhead compared to
connectionless protocols due to the additional control messages and the need to maintain
connection state information.
 Connection-oriented protocols are commonly used in applications where data
integrity, reliability, and ordered delivery are crucial.
 Examples include web browsing, email, file transfer, and other applications where
accurate data transmission is essential.
6
Network programming
 Network programming refers to the development of software applications that
communicate with other devices or systems over a network.
 It involves writing code to establish connections, exchange data, and manage
communication protocols between different devices or applications.
 Networking in Java involves the ability to communicate and exchange data between
different devices over a network.
 Java provides a rich set of libraries and classes to simplify networking tasks.
Communication
 Java provides two mechanisms for Network programming
 Socket-based communication (java socket programming) (java.net)

Sockets are the endpoints of two-way connections between two distributed components that
communicate with each other.
 Remote method invocation (RMI) (java.rmi)

RMI allows distributed components to be manipulated (almost) as if they were all on the same
host.

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

communication between devices, and ports distinguish different applications or


services running on a device.
 Together, IP, sockets, and ports enable network communication by specifying the

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

32-bit number, typically


Combination of an IP
Format represented in dotted- 16-bit number
address and a port number
decimal format

Example 192.168.1.1 (192.168.1.1, 80) 80

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{ }

ServerSocket ss=new ServerSocket(6666);


Socket s=ss.accept();
//establishes connection

DataInputStream dis=new DataInputStream(


s.getInputStream());

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.

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


// MyClient.java
import java.io.*; dout.close();
import java.net.*; s.close();
public class MyClient { }catch(Exception e){
public static void main(String[] args) { System.out.println(e)
try{ }
}
Socket s=new Socket("localhost",6666); }
DataOutputStream dout=new DataOutputStream(
s.getOutputStream());
dout.writeUTF("Hello Server"); 20
Example
Let's see another Java socket programming where client will write first to the
server then the server will receive and print the text.
Then server will write to the client and client will receive and print the text.

Look the next code…


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

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);

System.out.println("Server started. Waiting for client


connection...");

// Wait for a client to connect


Socket clientSocket = serverSocket.accept();

System.out.println("Client connected: " +


clientSocket.getInetAddress().getHostAddress());
23
Cont.
// Create input and output streams
for the client socket System.out.println("Server closed."
BufferedReader in = new } catch (IOException e) {
BufferedReader(new e.printStackTrace();
InputStreamReader(clientSocket.getInputStream() }
)); }
PrintWriter out = new }
PrintWriter(clientSocket.getOutputStream(),
true);
// Read client message and echo it back
String clientMessage =
in.readLine();
System.out.println("Received from
client: " + clientMessage);
out.println("Server echo: " +
clientMessage);
// Close the sockets and streams
in.close();
out.close();
clientSocket.close();
serverSocket.close();
24
Cont.
// Client Code
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) {
try {
// Create a socket and connect to the server
Socket socket = new Socket("localhost",
12345);
// Create input and output streams for the
socket
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new
PrintWriter(socket.getOutputStream(), true);

// Send a message to the server


String message = "Hello, server!";
out.println(message);
System.out.println("Sent to server: " +
25
message);
Cont.
// Receive the server's response
String serverResponse =
in.readLine();
System.out.println("Received
from server: " + serverResponse);

// Close the socket and streams


in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

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);

// Extract client's IP address and port number


InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();

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);

// Echo the message back to the client


byte[] sendData = clientMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, clientAddress, clientPort);
serverSocket.send(sendPacket);

// Close the server socket


serverSocket.close();

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();

// Define the server address and port number


InetAddress serverAddress = InetAddress.getByName("localhost");
int serverPort = 12345;

// Convert the message to bytes


String message = "Hello, server!";
byte[] sendData = message.getBytes();

// Create a DatagramPacket to send data to the server


DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, serverAddress, serverPort);

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);

// Receive the server's response


clientSocket.receive(receivePacket);

// Convert the received data to a string


String serverResponse = new
String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Received from server: " + 30
Remote method invocation (RMI)
 Is a scenario where having a program running on one machine invoke a method
belonging to an object whose execution is performed on another machine.
 Remote Method Invocation (RMI) is a Java technology that allows a Java object in one
JVM (Java Virtual Machine) to invoke methods on an object residing in another JVM,
 possibly on a different physical machine or network. RMI enables distributed
computing by providing a mechanism for remote communication between Java
applications.
 Communication: RMI enables communication between Java objects running in different
JVMs. It allows a client-side Java object to call methods on a server-side Java object
as if they were local method invocations.
 Interface Definition: RMI relies on interfaces to define the methods that can be invoked
remotely.
 These interfaces, known as remote interfaces, specify the methods that can be called by
remote clients.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy