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

Java Networking Basics and Examples

The document provides an overview of Java networking, detailing protocols like TCP and UDP, core classes in the java.net package, and the InetAddress class for handling IP addresses. It also covers TCP/IP socket programming for client-server communication, URL connections for data retrieval and posting, and the use of datagrams in UDP applications. Additionally, it introduces Enterprise JavaBeans (EJB) for building scalable enterprise applications, discussing their advantages, disadvantages, and types.

Uploaded by

bott19955
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)
5 views12 pages

Java Networking Basics and Examples

The document provides an overview of Java networking, detailing protocols like TCP and UDP, core classes in the java.net package, and the InetAddress class for handling IP addresses. It also covers TCP/IP socket programming for client-server communication, URL connections for data retrieval and posting, and the use of datagrams in UDP applications. Additionally, it introduces Enterprise JavaBeans (EJB) for building scalable enterprise applications, discussing their advantages, disadvantages, and types.

Uploaded by

bott19955
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

UNIT 5:

Networking Basics:
Java networking refers to writing programs that allow multiple devices (computers, servers, etc.) to
communicate over a network. This is done using the [Link] package, which provides classes and
interfaces for low-level communication.

1. Protocols: In networking, a protocol is a set of rules and conventions that determine how data
is transmitted and received across a network:
• TCP (Transmission Control Protocol): Reliable, connection-oriented protocol. Ensures data
arrives in order and without errors.

• UDP (User Datagram Protocol): Unreliable, connection-less protocol. Faster but no guarantee of
delivery or order

2. Core Classes in [Link]


Class Purpose
Socket Used for client-side TCP connections
ServerSocket Listens for incoming TCP connections
DatagramSocket Used for sending/receiving UDP packets
InetAddress Represents an IP address
URL Handles web addresses and data retrieval
3. Interfaces
• URLConnection: Abstracts the connection to a resource pointed by a URL.

• ContentHandler: Helps in processing content from a URL.

InetAdress
The InetAddress class in advanced Java is a powerful tool for handling IP addresses and hostnames.
It resides in the [Link] package and plays a central role in network programming. Here's a detailed
look:
What Is InetAddress?
The InetAddress class represents an IP address (either IPv4 or IPv6) and optionally a hostname. It’s
used to:

• Resolve hostnames to IP addresses

• Retrieve local or remote IP information

• Check address types (loopback, multicast, etc.)

Features of InetAddress
• No public constructors: You use static factory methods like getByName() or getLocalHost() to
create instances.

• Supports both IPv4 and IPv6: It’s the superclass of Inet4Address and Inet6Address.

• Encapsulates hostname and IP: Useful for DNS lookups and reverse lookups.

Common Methods
Method Description
getByName(String host) Returns InetAddress for a hostname or IP string
getAllByName(String host) Returns all IPs associated with a hostname
getLocalHost() Returns the local machine’s IP address
getHostName() Returns the hostname of the IP
getHostAddress() Returns the IP address in string format
isLoopbackAddress() Checks if the address is a loopback
isMulticastAddress() Checks if the address is multicast
getCanonicalHostName() Returns the fully qualified domain name

Example:

import [Link].*;
public class InetExample {

public static void main(String[] args) throws Exception {

InetAddress address = [Link]("[Link]");


[Link]("Host Name: " + [Link]());

[Link]("IP Address: " + [Link]());

InetAddress local = [Link]();


[Link]("Local Host: " + [Link]());

Output:

Host Name: [Link]

IP Address: [Link]

Local Host: your-machine-name

TCP/IP client-server socket


TCP/IP client-server socket programming is a foundational technique for building networked
applications. It enables reliable, bidirectional communication between two machines using the TCP
protocol. Here's a complete breakdown:

TCP/IP Socket Programming in Java


Server Side (Using ServerSocket)
Example:
import [Link].*;
import [Link].*;

public class Server {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
[Link]("Server is listening on port 5000...");
Socket socket = [Link]();
[Link]("Client connected");

DataInputStream input = new DataInputStream([Link]());


String message = [Link]();
[Link]("Received: " + message);
[Link]();
} catch (IOException ex) {
[Link]();
}
}
}

Client Side (Using Socket)


import [Link].*;
import [Link].*;

public class Client {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)) {
[Link]("Connected to server");

DataOutputStream output = new DataOutputStream([Link]());


[Link]("Hello from client!");

[Link]();
} catch (IOException ex) {
[Link]();
}
}
}

Concept Description
ServerSocket Listens for incoming TCP connections
Socket Represents a client-side connection
DataInputStream /
Used for reading/writing data over the socket
DataOutputStream
Port Numerical identifier for a specific service (e.g., 5000)
IP Address Identifies the host machine (e.g., localhost or [Link])
URL connection
The URL Connection class in Java is part of the [Link] package and is used to represent a
communication link between an application and a URL. It provides methods to read from and write
to the resource referenced by the URL.

Features of URL Connection:


1. Abstract Class: URL Connection is an abstract class, and its concrete implementation depends on
the protocol (e.g., HTTP, FTP).
2. Protocol Independence: It supports various protocols like HTTP, HTTPS, FTP, etc.
3. Read/Write Operations: You can use it to read data from or write data to the resource.
4. Header Management: It allows you to set and retrieve HTTP headers.
5. Caching: It supports caching of resources.

Example: Using URLConnection to Read Data from a URL


Here is a simple example to demonstrate how to use URLConnection to fetch and display the
content of a web page:
import [Link];
import [Link];
import [Link];
import [Link];

public class ReadFromURL {


public static void main(String[] args) {
try {
// 1. Create a URL object
URL url = new URL("[Link]

// 2. Open a connection to the URL


URLConnection connection = [Link]();

// 3. Create a BufferedReader to read the input stream


BufferedReader reader = new BufferedReader(
new InputStreamReader([Link]())
);

// 4. Read and print lines from the website


String line;
while ((line = [Link]()) != null) {
[Link](line);
}
// 5. Close the reader
[Link]();

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

Example: Writing Data to a URL (HTTP POST)


If you want to send data to a server (e.g., via HTTP POST), you can use the URLConnection class
as follows:
import [Link];
import [Link];
import [Link];

public class SimpleHttpPost {


public static void main(String[] args) {
try {
URL url = new URL("[Link]
HttpURLConnection conn = (HttpURLConnection) [Link]();

[Link]("POST");
[Link](true);
[Link]("Content-Type", "application/json");

String json = "{\"title\":\"Hello\",\"body\":\"World\",\"userId\":1}";

try (OutputStream os = [Link]()) {


[Link]([Link]("utf-8"));
}
[Link]("Response Code: " + [Link]());
} catch (Exception e) {
[Link]();
}
}
}
HTTP URL Connection:
HTTP URL Connection" generally refers to the use of the HttpURLConnection class in Java to
establish HTTP connections with web servers. It's part of the Java standard library and allows
sending HTTP requests (GET, POST, etc.) and reading responses.

Example of using HttpURLConnection in Java to perform a GET request from a


URL.
import [Link];
import [Link];
import [Link];
import [Link];

public class SimpleHttpGet {


public static void main(String[] args) {
try {
// 1. Create a URL object
URL url = new URL("[Link]

// 2. Open a connection
HttpURLConnection connection = (HttpURLConnection) [Link]();

// 3. Set the request method to GET


[Link]("GET");

// 4. Get the response code


int responseCode = [Link]();
[Link]("Response Code: " + responseCode);

// 5. Read the response if it's OK (200)


if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]())
);
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = [Link]()) != null) {


[Link](inputLine);
}
[Link]();
[Link]("Response Body:\n" + [Link]());
} else {
[Link]("GET request failed.");
}
} catch (Exception e) {
[Link]();
}
}
}

Java POST Example using HttpURLConnection


Java POST Example using HttpURLConnection
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SimpleHttpPost {


public static void main(String[] args) {
try {
URL url = new URL("[Link]
HttpURLConnection connection = (HttpURLConnection) [Link]();

[Link]("POST");

[Link]("Content-Type", "application/json; utf-8");


[Link]("Accept", "application/json");

[Link](true);

String jsonInput = "{\"title\": \"Hello\", \"body\": \"World\", \"userId\": 1}";

try (OutputStream os = [Link]()) {


byte[] input = [Link]("utf-8");
[Link](input, 0, [Link]);
}

int responseCode = [Link]();


[Link]("Response Code: " + responseCode);

try (BufferedReader reader = new BufferedReader(


new InputStreamReader([Link](), "utf-8"))) {

StringBuilder response = new StringBuilder();


String line;

while ((line = [Link]()) != null) {


[Link]([Link]());
}

[Link]("Response Body:\n" + [Link]());


}

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

Datagram
A Datagram in Java refers to a packet of data sent or received using the UDP protocol (User
Datagram Protocol), which is a connectionless, lightweight, and fast protocol used in real-time
applications like games, video streaming, or VoIP.
In Java, you can work with datagrams using these classes from the [Link] package:
• DatagramSocket – used to send or receive datagram packets.
• DatagramPacket – represents the data sent or received.

Simple Datagram Example (Java UDP)


We'll create two simple programs:

UDP Sender (Client)

Sends a message to a specific IP and port.

import [Link];
import [Link];
import [Link];

public class UdpSender {


public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();

String message = "Hello, UDP Receiver!";


byte[] buffer = [Link]();

InetAddress receiverAddress = [Link]("localhost");


int port = 9876;

DatagramPacket packet = new DatagramPacket(buffer, [Link], receiverAddress, port);


[Link](packet);

[Link]("Message sent.");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

UDP Receiver (Server)


Listens on a port and prints received messages.
import [Link];
import [Link];

public class UdpReceiver {


public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(9876);
byte[] buffer = new byte[1024];

[Link]("Waiting for message...");

DatagramPacket packet = new DatagramPacket(buffer, [Link]);


[Link](packet); // Blocking call

String received = new String([Link](), 0, [Link]());


[Link]("Received: " + received);

[Link]();
} catch (Exception e) {
[Link]();
}
}
}
EJB
EJB stands for Enterprise JavaBeans — a server-side component architecture used in Java EE
(now Jakarta EE) for building scalable, distributed, transactional, and secure enterprise-level
applications.

What is EJB?
EJB is used to encapsulate business logic in reusable components. The EJB container (like in an
application server such as WildFly, GlassFish, etc.) manages things like:
• Transactions
• Security
• Concurrency
• Remoting
• Lifecycle management

When to use Enterprise Java Beans


[Link] needs Remote Access. In other words, it is distributed.
[Link] needs to be scalable. EJB applications supports load balancing, clustering and fail-
over.
[Link] needs encapsulated business logic. EJB application is differentiated from
demonstration and persistent layer.

Advantages of Enterprise Java Beans


1. Simplified Development of Enterprise Applications
2. Built-in Transaction Management
3. Security Management
4. Remote Accessibility
5. Scalability and Load Balancing

Disadvantages of Enterprise Java Beans


1. Requires application server
2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop EJB applications.

Types of Enterprise Java Beans


There are three types of EJB:
1. Session Bean: Session bean contains business logic that can be invoked by local, remote or
webservice client. There are two types of session beans: (i) Stateful session bean and (ii) Stateless
session bean.

• (i) Stateful Session bean :


Stateful session bean performs business task with the help of a state. Stateful session bean can be
used to access various method calls by storing the information in an instance variable. Some of the
applications require information to be stored across separate method calls. In a shopping site, the
items chosen by a customer must be stored as data is an example of stateful session bean.

• (ii) Stateless Session bean :


Stateless session bean implement business logic without having a persistent storage mechanism,
such as a state or database and can used shared data. Stateless session bean can be used in situations
where information is not required to used across call methods.

2. Message Driven Bean: Like Session Bean, it contains the business logic but it is invoked by
passing message.
3. Entity Bean: It summarizes the state that can be remained in the database. It is deprecated.
Now, it is replaced with JPA (Java Persistent API). There are two types of entity bean:

• (i) Bean Managed Persistence :


In a bean managed persistence type of entity bean, the programmer has to write the code for
database calls. It persists across multiple sessions and multiple clients.

• (ii) Container Managed Persistence :


Container managed persistence are enterprise bean that persists across database. In container
managed persistence the container take care of database calls.

You might also like