0% found this document useful (0 votes)
2 views30 pages

Java Networking Basics

The document provides an overview of Java Networking, detailing the `java.net` package and its classes for IP addressing, URL handling, and client-server communication. It includes examples of TCP and UDP programming, explaining the differences between the two protocols, and demonstrates how to use classes like `Socket`, `ServerSocket`, `DatagramSocket`, and `URLConnection`. Additionally, it covers practical applications of Java Networking in chat applications, file transfers, and web services.

Uploaded by

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

Java Networking Basics

The document provides an overview of Java Networking, detailing the `java.net` package and its classes for IP addressing, URL handling, and client-server communication. It includes examples of TCP and UDP programming, explaining the differences between the two protocols, and demonstrates how to use classes like `Socket`, `ServerSocket`, `DatagramSocket`, and `URLConnection`. Additionally, it covers practical applications of Java Networking in chat applications, file transfers, and web services.

Uploaded by

subathankaraj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Networking Basics

Java Networking allows Java programs to communicate over a network (LAN / Internet) using built-in
classes from the `[Link]` package.

1. Java Networking Package

``java

import [Link].;

```

This package provides classes for:

IP addressing

URL handling

Client–server communication

TCP & UDP programming

2. Important Java Networking Classes

Class Purpose

`InetAddress` Represents IP address

`URL` Represents a web address

`URLConnection` Communication with URL

`Socket` Client-side TCP communication


`ServerSocket` Server-side TCP

`DatagramSocket` UDP communication

`DatagramPacket` UDP packet

3. InetAddress Example (IP Address)

```java

import [Link].;

class InetExample {

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

InetAddress ip = [Link]();

[Link](ip);

```

4. URL Example

```java

import [Link].;
class URLExample {

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

URL url = new URL("[Link]

[Link]("Protocol: " + [Link]());

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

```

5. Socket Programming (TCP)

Client Program

```java

import [Link].;

import [Link].;

class Client {

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

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

DataOutputStream dout =

new DataOutputStream([Link]());
[Link]("Hello Server");

[Link]();

[Link]();

```

Server Program

```java

import [Link].;

import [Link].;

class Server {

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

ServerSocket ss = new ServerSocket(1234);

Socket s = [Link]();

DataInputStream din =

new DataInputStream([Link]());

[Link]([Link]());

[Link]();

}
}

```

6. UDP Programming (Datagram)

Faster

No connection

No guarantee of delivery

Uses:

`DatagramSocket`

`DatagramPacket`

7. TCP vs UDP in Java

TCP UDP

- -

Reliable Unreliable

Connection-oriented Connectionless

Uses Socket Uses DatagramSocket


Slower Faster

8. Java Networking Applications

Chat applications

Client–server systems

File transfer

Online games

Web service

InetAddress in Java

InetAddress is a Java class used to represent an IP address (IPv4 or IPv6).

It belongs to the `[Link]` package and is widely used in Java networking.

1. What is InetAddress?

Represents IP address + host name

Supports IPv4 and IPv6

Used to identify a machine on a network

Abstract class
```java

import [Link];

```

2. Commonly Used Methods

Method Description

`getLocalHost()` Returns local system IP

`getByName(String host)` Returns IP of given host

`getAllByName(String host)` Returns all IPs

`getHostName()` Returns host name

`getHostAddress()` Returns IP address

`isReachable(int timeout)` Checks reachability

3. Example: Local Host Information

```java

import [Link].;

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

InetAddress ip = [Link]();

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

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

```

4. Example: Get IP of Website

```java

import [Link].;

class InetWebsite {

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

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

[Link]([Link]());

```

-
5. Example: All IPs of a Host

```java

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

for (InetAddress ip : ips) {

[Link](ip);

```

6. Important Points (Exam ⭐)

Part of `[Link]` package

Used for IP addressing

Abstract class

Supports IPv4 and IPv6

No public constructor (uses factory methods)

7. InetAddress vs URL

InetAddress URL

-
Represents IP/host Represents complete web address

No protocol Has protocol

Network identification Resource location

8. Real-Time Uses

Ping applications

Client–server programs

Network diagnostics

Chat applications

TCP/IP Client Sockets in Java

In Java, a TCP/IP client socket is used by a client program to connect to a server over a network using the
TCP protocol (reliable, connection-oriented).

Java provides this through the `Socket` class in the `[Link]` package.

1. What is a Client Socket?

A client socket initiates a connection

Connects to a server IP address + port number

Uses TCP/IP
Ensures reliable data transfer

2. Packages Used

```java

import [Link].;

import [Link].;

```

3. How TCP Client Socket Works (Steps)

1. Client creates a `Socket`

2. Socket connects to server (IP + port)

3. Client sends data to server

4. Client receives response

5. Connection closes

4. Important Classes
Class Use

`Socket` Creates client socket

`InputStream` Receives data

`OutputStream` Sends data

`DataInputStream` Reads data

`DataOutputStream` Writes data

5. Simple TCP Client Program (Java)

Client Program

```java

import [Link].;

import [Link].;

class TCPClient {

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

// 1. Create socket (server IP, port)

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

// 2. Send data to server


DataOutputStream dout =

new DataOutputStream([Link]());

[Link]("Hello Server");

// 3. Receive response from server

DataInputStream din =

new DataInputStream([Link]());

[Link]("Server says: " + [Link]());

// 4. Close connection

[Link]();

```

6. Server Program (For Understanding)

```java

import [Link].;

import [Link].;

class TCPServer {

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


ServerSocket ss = new ServerSocket(1234);

Socket s = [Link]();

DataInputStream din =

new DataInputStream([Link]());

[Link]("Client says: " + [Link]());

DataOutputStream dout =

new DataOutputStream([Link]());

[Link]("Hello Client");

[Link]();

```

7. TCP Client Socket Features

✔ Reliable communication

✔ Data arrives in order

✔ Error checking

✔ Connection-oriented
-

8. TCP vs UDP (Exam Point ⭐)

TCP UDP

- -

Reliable Unreliable

Connection-oriented Connectionless

Uses `Socket` Uses `DatagramSocket`

Slower Faster

9. Real-Life Applications

Chat applications

File transfer

Client–server systems

Web browsers

TCP/IP ServerSocket in Java

In Java, ServerSocket is used to create a TCP server that listens for and accepts connections from client
sockets.
It is part of the `[Link]` package and works with the TCP/IP protocol.

1. What is ServerSocket?

Represents a server-side socket

Listens on a port number

Accepts client connection requests

Used for TCP (connection-oriented) communication

2. Packages Required

```java

import [Link].;

import [Link].;

```

3. How TCP ServerSocket Works (Steps)

1. Server creates a `ServerSocket` on a port


2. Server waits for client request (`accept()`)

3. Connection established (Socket created)

4. Data exchange happens

5. Connection closes

4. Important Classes

Class Purpose

`ServerSocket` Listens for clients

`Socket` Communication with client

`InputStream` Receive data

`OutputStream` Send data

5. Simple TCP Server Program

```java

import [Link].;

import [Link].;

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

// 1. Create server socket on port 1234

ServerSocket ss = new ServerSocket(1234);

[Link]("Server waiting for client...");

// 2. Accept client connection

Socket s = [Link]();

[Link]("Client connected");

// 3. Read data from client

DataInputStream din =

new DataInputStream([Link]());

String msg = [Link]();

[Link]("Client says: " + msg);

// 4. Send response to client

DataOutputStream dout =

new DataOutputStream([Link]());

[Link]("Hello Client");

// 5. Close connection

[Link]();

[Link]();

}
}

```

6. Key Methods of ServerSocket

Method Description

`accept()` Waits for client

`close()` Closes server

`getLocalPort()` Returns port number

`isClosed()` Checks if closed

7. ServerSocket vs Socket

ServerSocket Socket

Server-side Client-side

Listens Connects

Accepts client Sends request

Uses `accept()` Uses constructor


-

8. TCP Server Features

✔ Reliable data transfer

✔ Connection-oriented

✔ Secure communication

1. What is a URL?

A URL specifies the location of a resource on the network.

Example URL

[Link]

2. Parts of a URL

protocol://host:port/path?queryref

Part Example

- -

Protocol https

Host [[Link]]([Link]

Port 443

Path /[Link]

Query ?id=10

Reference top

URL Class in Java

```java

import [Link];
4. Creating a URL Object

```java

URL url = new URL("[Link]

5. Important URL Methods

Method Description

`getProtocol()` Returns protocol

`getHost()` Returns host name

`getPort()` Returns port number

`getFile()` Returns file/path

`getPath()` Returns path

`getQuery()` Returns query

`openStream()` Reads data from URL

`openConnection()` Returns URLConnection

6. Example: URL Information Program

```java

import [Link].;

class URLInfo {

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

URL url = new URL("[Link]

[Link]("Protocol: " + [Link]());

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

[Link]("Path: " + [Link]());

[Link]("Query: " + [Link]());

}
}

7. Reading Data from URL

`java

import [Link].;

import [Link].;

class URLRead {

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

URL url = new URL("[Link]

BufferedReader br =

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

String line;

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

[Link](line);

[Link]();

8. URL vs InetAddress

URL InetAddress

Complete web address Only IP/host

Can read data Cannot read data

Protocol included No protocol

9. Uses of URL in Java

Access web pages


Download data

Network applications

Web services

1. What is URLConnection?

Represents a communication link between Java program and URL

Used to read data from a URL

Can also send data (HTTP requests)

Abstract class

2. Creating URLConnection Object

```java

URL url = new URL("[Link]

URLConnection con = [Link]();

```

3. Important URLConnection Methods

Method Description
`connect()` Opens connection

`getInputStream()` Reads data

`getOutputStream()` Writes data

`getContentType()` Returns MIME type

`getContentLength()` Returns content size

`getLastModified()` Returns last modified time

`getHeaderFields()` Returns header info

4. Example: Read Data Using URLConnection

```java

import [Link].;

import [Link].;

class URLConnectionExample {

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

URL url = new URL("[Link]

URLConnection con = [Link]();

BufferedReader br =

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


String line;

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

[Link](line);

[Link]();

```

5. HTTPURLConnection (Important)

`HttpURLConnection` is a subclass of URLConnection

Used specifically for HTTP/HTTPS communication

```java

HttpURLConnection con =

(HttpURLConnection) [Link]();

```

6. Common HTTP Methods


GET

POST

PUT

DELETE

7. URLConnection vs URL

URL URLConnection

Represents address Represents connection

Cannot transfer data Transfers data

No headers Has headers

8. Uses of URLConnection

Access web pages

Download files

REST API calls

Web services

9. Exam Tip ⭐

Datagram in Java (UDP)

In Java, a Datagram is a packet of data sent using the UDP (User Datagram Protocol).

UDP communication is connectionless, fast, but unreliable.


Java supports datagrams using classes from the `[Link]` package.

1. What is a Datagram?

A small packet of data

Sent using UDP

No connection setup

No guarantee of delivery or order

2. Java Classes Used for Datagram

Class Purpose

`DatagramPacket` Represents the data packet

`DatagramSocket` Sends & receives packets

3. DatagramPacket

Represents the actual data being sent or received.


Constructors

```java

DatagramPacket(byte[] buf, int length);

DatagramPacket(byte[] buf, int length, InetAddress addr, int port);

` 4. DatagramSocket

Used to send and receive datagram packets.

```java

DatagramSocket ds = new DatagramSocket();

5. UDP Datagram Example

Sender (Client)

```java

import [Link].;

class DatagramSender {

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

DatagramSocket ds = new DatagramSocket();

String msg = "Hello UDP";

byte[] data = [Link]();

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

DatagramPacket dp =
new DatagramPacket(data, [Link], ip, 1234);

[Link](dp);

[Link]();

Receiver (Server)

`java

import [Link].;

class DatagramReceiver {

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

DatagramSocket ds = new DatagramSocket(1234);

byte[] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, [Link]);

[Link](dp);

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

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

[Link]();

```

6. Datagram vs TCP (Exam ⭐)


Datagram (UDP) TCP

Connectionless Connection-oriented

Fast Slower

Unreliable Reliable

Uses DatagramSocket Uses Socket

7. Uses of Datagram (UDP)

Online games

Live streaming

Voice/video calls

DNS services

You might also like