[go: up one dir, main page]

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

Attachment

This document provides an overview of Java networking concepts, focusing on sockets, including client and server sockets, reserved sockets, and proxy servers. It explains the roles of TCP, UDP, and various classes in Java for handling network communication, such as InetAddress, DatagramSocket, and URL. Additionally, it includes examples of server and client programs for both TCP and UDP communication.

Uploaded by

adityapandji1
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 views18 pages

Attachment

This document provides an overview of Java networking concepts, focusing on sockets, including client and server sockets, reserved sockets, and proxy servers. It explains the roles of TCP, UDP, and various classes in Java for handling network communication, such as InetAddress, DatagramSocket, and URL. Additionally, it includes examples of server and client programs for both TCP and UDP communication.

Uploaded by

adityapandji1
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
You are on page 1/ 18

Java Programming

Chapter 5 - K Scheme
Basics of Network Programming
Notes

Quote of the day: The expert in anything was once a beginner

Socket Overview

In Java networking, a socket is one endpoint of a two-way communication link between two
programs running on the network. A socket is bound to a port number so that the
Transmission Control Protocol (TCP) or User Datagram Protocol (UDP) layer can
identify the application that data is destined for.

What is a Socket ?

A socket acts as an interface between the application and the network.

 It allows the application to send and receive data over the network.
 Java provides different classes for implementing sockets in the java.net package.

Client and Server Socket

In Java networking, client and server sockets are used to establish a TCP connection for
reliable communication between two systems. The server socket listens for incoming
connections, while the client socket initiates the connection.

Client Socket

 Represented by the Socket class in Java.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


 Used by the client to initiate a connection to a server.
 Once connected, it can send and receive data using input/output streams.
 Requires the server IP address and port number to connect.
 Constructor - Socket socket = new Socket(String host, int port);
 Example - Socket socket = new Socket("localhost", 5000);

Server Socket

 Represented by the ServerSocket class in Java.


 Used by the server to listen for incoming client connection.
 It waits for a client to connect using the accept() method.
 After connection, it returns a Socket object to communicate with the client.

Constructor:
ServerSocket serverSocket = new ServerSocket(int port);

Example:
ServerSocket serverSocket = new ServerSocket(5000);Socket clientSocket =
serverSocket.accept();

Reserved Socket

Reserved sockets refer to a range of port numbers that are predefined or reserved by the
Internet Assigned Numbers Authority (IANA) for specific services and protocols. These
sockets are not specific to Java but are important to understand while writing Java networking
programs.

What is a Reserved Socket?

 A socket is identified by a combination of IP address and port number.


 Reserved sockets use well-known port numbers (from 0 to 1023) which are
reserved for standard services.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


 These ports require administrative privileges to bind on most systems (especially
Unix/Linux).

Port Number Ranges


Range Description
0 – 1023 Well-known / Reserved ports (e.g., HTTP, FTP, SMTP)
1024 – 49151 Registered ports (can be used by user processes)
49152 – 65535 Dynamic/Private ports (usually assigned dynamically)

Examples of Reserved Ports


Port Number Service
20, 21 FTP
22 SSH
23 Telnet
25 SMTP (Email)
53 DNS
80 HTTP (Web)
443 HTTPS (Secure Web)

Proxy Server

A proxy server is an intermediate server that sits between a client and the main server. It
acts as a gateway, handling requests from the client and forwarding them to the actual server.
The response from the server is then sent back to the client through the proxy.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Functions of a Proxy Server

 Hides client’s IP address (adds a layer of anonymity)


 Filters requests (for security or content control)
 Caches data (to improve performance
 Controls internet usage (used in schools/offices)

Working of a Proxy Server

 Client sends a request to the proxy server (e.g., to access a website).


 Proxy server forwards the request to the actual server.
 Server sends the response back to the proxy.
 Proxy sends the data to the client.

InetAddress Class

The InetAddress class in Java is part of the java.net package and is used to represent an IP
address (both IPv4 and IPv6) of a host (either local or remote). It provides methods to
resolve hostnames to IP addresses and vice versa.

Key Feature

 Represents both domain names and IP addresses.


 Can be used to find the local host IP, remote server IP, or hostname.
 Supports DNS lookup and reverse lookup.

Commonly Used Methods

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Method Description
getByName(String host) Returns the InetAddress object for the specified host name.
getLocalHost() Returns the InetAddress object of the local machine.
getHostName() Returns the host name of the IP address.
getHostAddress() Returns the IP address in string format.
getAllByName(String host) Returns all IP addresses associated with a domain name.

Example :

import java.net.*;

public class InetExample {

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

InetAddress address = InetAddress.getByName("www.google.com");

System.out.println("Host Name: " + address.getHostName());

System.out.println("IP Address: " + address.getHostAddress());

Example 2 :

InetAddress local = InetAddress.getLocalHost();

System.out.println("Local Host Name: " + local.getHostName());

System.out.println("Local IP Address: " + local.getHostAddress());

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


TCP, IP, and UDP
TCP, IP, and UDP are core networking protocols that govern how data is sent and received
over the internet. Java networking is built on top of these protocols to allow communication
between computers.

IP (Internet Protocol)

 IP is the foundational protocol that routes data from the source to the destination
across networks.
 It breaks data into packets and labels them with the sender's and receiver's IP
addresses.
 IP is connectionless and does not guarantee delivery, order, or error checking.

✅ Responsibilities of IP:

 Addressing (IPv4 or IPv6)


 Packet routing
 Packet fragmentation

TCP (Transmission Control Protocol)

 TCP is a connection-oriented protocol built on top of IP.


 It ensures reliable, ordered, and error-checked delivery of data.
 TCP establishes a connection between sender and receiver before data transfer (3-
way handshake).

✅ Features:

 Reliable delivery
 Acknowledgement of data
 Resends lost packet
 Maintains order

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Example in Java:

Java uses Socket and ServerSocket classes for TCP communication.

UDP (User Datagram Protocol)

 UDP is a connectionless protocol, also built on top of IP.


 It is faster than TCP but does not guarantee delivery, order, or error correction.
 Suitable for applications where speed is more important than reliability (e.g.,
video streaming, online gaming).

✅ Features:

 No connection setup
 Low latency
 Best-effort delivery (no guarantee)

Example in Java:

Java uses DatagramSocket and DatagramPacket classes for UDP communication.

TCP / IP Server Socket

In Java, a TCP/IP server socket allows a server program to listen for incoming TCP
connections from client programs over the network. It is implemented using the
ServerSocket class in the java.net package.

What is a Server Socket?

 A ServerSocket waits for requests from clients.


 It listens on a specific port number.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


 When a client connects, the server socket creates a new Socket object to handle
communication with that client.

TCP/IP Communication Steps

 Server creates a ServerSocket and waits for clients.


 Client connects using a Socket.
 Server accepts the connection using accept() method.
 Server and client communicate using InputStream and OutputStream.
 After communication, both sockets are closed.

Important ServerSocket Methods

Method Description
ServerSocket(int port) Creates a server socket on the specified port
accept() Waits for a client to connect and returns a new Socket
close() Closes the server socket

Example of sending hello from client to server

Server Program

// File: TCPServer.java

import java.io.*;

import java.net.*;

public class TCPServer {

public static void main(String[] args) {

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


try {

ServerSocket serverSocket = new ServerSocket(5000); // Server listens on port 5000

System.out.println("Server is waiting for client...");

Socket socket = serverSocket.accept(); // Accept client connection

System.out.println("Client connected!");

// Receive message from client

BufferedReader reader = new BufferedReader(new


InputStreamReader(socket.getInputStream()));

String clientMessage = reader.readLine();

System.out.println("Client says: " + clientMessage);

// Send response to client

PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

writer.println("Hello Client, message received!");

// Close connections

reader.close();

writer.close();

socket.close();

serverSocket.close();

} catch (IOException e) {

e.printStackTrace();

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


}

Client Program

// File: TCPClient.java

import java.io.*;

import java.net.*;

public class TCPClient {

public static void main(String[] args) {

try {

Socket socket = new Socket("localhost", 5000); // Connect to server on port 5000

// Send message to server

PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

writer.println("Hello Server!");

// Receive response from server

BufferedReader reader = new BufferedReader(new


InputStreamReader(socket.getInputStream()));

String serverMessage = reader.readLine();

System.out.println("Server says: " + serverMessage);

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


// Close connections

writer.close();

reader.close();

socket.close();

} catch (IOException e) {

e.printStackTrace();

Datagram in Java
In Java networking, a Datagram is a self-contained, independent packet of data sent over a
UDP (User Datagram Protocol) connection. Unlike TCP, UDP is connectionless, meaning
there is no need to establish a connection between the sender and receiver.

Java provides the following classes for handling datagrams:

 DatagramSocket – Used for sending and receiving datagram packets.


 DatagramPacket – Represents the actual data packet to be sent or received

Key Features of Datagram (UDP)

 Connectionless: No need to establish or maintain a connection.


 Faster but Unreliable: No guarantee of delivery, order, or error checking.
 Used for: Live streaming, gaming, DNS lookups, etc

Datagram Communication Steps

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


 Server creates a DatagramSocket to listen on a port.
 Client creates a DatagramSocket and sends a DatagramPacket to the server’s IP
and port.
 Server receives the packet and sends a response
 Client receives the server's response.

Example -:

Server Program

// File: UDPServer.java

import java.net.*;

public class UDPServer {

public static void main(String[] args) {

try {

DatagramSocket serverSocket = new DatagramSocket(6000);

byte[] receiveBuffer = new byte[1024];

System.out.println("Server is running and waiting for client message...");

// Receive message from client

DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,


receiveBuffer.length);

serverSocket.receive(receivePacket);

String clientMessage = new String(receivePacket.getData(), 0,

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


receivePacket.getLength());

System.out.println("Client says: " + clientMessage);

// Send response to client

String response = "Hello Client, message received!";

byte[] sendBuffer = response.getBytes();

InetAddress clientAddress = receivePacket.getAddress();

int clientPort = receivePacket.getPort();

DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,


clientAddress, clientPort);

serverSocket.send(sendPacket);

serverSocket.close();

} catch (Exception e) {

e.printStackTrace();

Client Program

// File: UDPClient.java

import java.net.*;

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


public class UDPClient {

public static void main(String[] args) {

try {

DatagramSocket clientSocket = new DatagramSocket();

InetAddress serverAddress = InetAddress.getByName("localhost");

String message = "Hello Server!";

byte[] sendBuffer = message.getBytes();

// Send message to server

DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,


serverAddress, 6000);

clientSocket.send(sendPacket);

// Receive response from server

byte[] receiveBuffer = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,


receiveBuffer.length);

clientSocket.receive(receivePacket);

String serverReply = new String(receivePacket.getData(), 0,


receivePacket.getLength());

System.out.println("Server says: " + serverReply);

clientSocket.close();

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


} catch (Exception e) {

e.printStackTrace();

URI Class in Java


The URI (Uniform Resource Identifier) class is part of the java.net package and is used to
represent and manipulate URI references. A URI is a string that identifies a resource on the
internet or a local system.

It is more general than a URL (Uniform Resource Locator). Every URL is a


URI, but not every URI is a URL.

Key Methods of URI Class


Method Description
getScheme() Returns the scheme (e.g., http, https)
getHost() Returns the host (e.g., www.google.com)
getPath() Returns the path part
getQuery() Returns the query string
getFragment() Returns the fragment part (if any)
isAbsolute() Checks if URI has a scheme
normalize() Normalizes the URI path

Example

import java.net.*;

public class URIExample {

public static void main(String[] args) {

try {

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


URI uri = new
URI("https://www.example.com/products/item.html?code=100#specs");

System.out.println("Scheme : " + uri.getScheme());

System.out.println("Host : " + uri.getHost());

System.out.println("Path : " + uri.getPath());

System.out.println("Query : " + uri.getQuery());

System.out.println("Fragment : " + uri.getFragment());

} catch (URISyntaxException e) {

e.printStackTrace();

URL Class in Java


The URL (Uniform Resource Locator) class in Java is part of the java.net package. It
represents the address of a resource on the internet and allows Java programs to connect to
that resource for reading or writing data.

Common Methods of URL Class


Method Description
getProtocol() Returns the protocol used (e.g., http)
getHost() Returns the hostname
getPort() Returns the port number
getPath() Returns the path of the resource
getQuery() Returns the query string
openConnection() Opens a connection to the resource
openStream() Opens a stream to read the resource content

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Example -:

import java.net.*;

import java.io.*;

public class URLExample {

public static void main(String[] args) {

try {

URL url = new URL("https://www.example.com");

System.out.println("Protocol: " + url.getProtocol());

System.out.println("Host : " + url.getHost());

System.out.println("Path : " + url.getPath());

// Read content from the URL

BufferedReader reader = new BufferedReader(new


InputStreamReader(url.openStream()));

String line;

System.out.println("\nWebsite Content:");

while ((line = reader.readLine()) != null) {

System.out.println(line);

reader.close();

} catch (Exception e) {

e.printStackTrace();

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


}

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND

You might also like