Network Programming Concepts Quiz
Unit 1. Introduction : 3 hrs
Introduction to Network Programming (3 Hours)
Network programming is the practice of writing programs that enable communication between devices or processes over a network. This field focuses on utilizing networking protocols, APIs, and tools to create robust client-server applications. The applications of network programming range from web services to distributed systems, making it an essential component of modern software development.
1.1 Network Programming Features and Scope
Features of Network Programming
-
Inter-device Communication:
- Enables interaction between devices across local and global networks.
- Examples include HTTP requests, file transfers, and streaming.
-
Platform Independence:
- Many networking libraries and frameworks are platform-independent, allowing developers to create applications that work seamlessly across various operating systems.
-
Protocol Support:
- Network programming incorporates support for numerous protocols such as TCP/IP, UDP, HTTP, FTP, and more.
-
Scalability:
- Provides mechanisms to build systems that handle multiple clients and requests efficiently, including load balancing and distributed processing.
-
Security Features:
- Integration of encryption standards like SSL/TLS ensures secure communication over the network.
-
Error Handling:
- Includes features for detecting and recovering from network failures, such as timeouts and retries.
Scope of Network Programming
- Web Development: Backend services using HTTP/HTTPS.
- IoT Applications: Device communication over MQTT or CoAP.
- Cloud Computing: Implementing APIs and services for remote resources.
- Real-time Applications: Chat applications, video conferencing, and multiplayer gaming.
- Distributed Systems: Frameworks like Hadoop and Spark for data processing across multiple nodes.
1.2 Network Programming Languages, Tools, and Platforms
Languages for Network Programming
- Java:
- Provides robust libraries like
java.netfor socket programming andHttpURLConnectionfor web services.
- Provides robust libraries like
- Python:
- Includes libraries such as
socket,requests, and frameworks like Flask and Django for web development.
- Includes libraries such as
- C/C++:
- Low-level control over networking using BSD sockets, suitable for performance-critical applications.
- JavaScript:
- Primarily used in web applications through frameworks like Node.js.
- Go:
- Known for its concurrency model, making it ideal for network-heavy applications.
Tools for Network Programming
- Postman:
- A widely-used tool for API testing and development.
- Wireshark:
- A network packet analyzer to debug and monitor communication.
- cURL:
- Command-line tool for transferring data using various protocols.
- Netcat:
- A versatile tool for testing and troubleshooting network connections.
Platforms
- Web Platforms: AWS, Azure, and Google Cloud for hosting services.
- Frameworks: Spring Boot (Java), Flask (Python), and Express (JavaScript).
- Operating Systems: Networking features in Linux and Windows.
- Protocol Libraries: OpenSSL for security and libcurl for multi-protocol support.
1.3 Client and Server Applications
Client Applications
- Definition:
- Software that initiates communication with a server to request resources or services.
- Examples:
- Web browsers (e.g., Chrome, Firefox).
- Email clients (e.g., Outlook, Thunderbird).
- Mobile apps accessing cloud services.
- Key Components:
- Request Mechanism: Uses protocols like HTTP or FTP.
- User Interface: Allows interaction with the end-user.
Server Applications
- Definition:
- Programs designed to handle requests from clients and provide responses or services.
- Examples:
- Web servers (e.g., Apache, Nginx).
- Database servers (e.g., MySQL, PostgreSQL).
- Media streaming servers.
- Key Components:
- Request Listener: Accepts client requests.
- Processing Logic: Handles data and executes business logic.
- Response Mechanism: Sends results back to the client.
1.4 Client-Server Model and Software Design
Client-Server Model
- Overview:
- A distributed architecture where the client requests services, and the server processes those requests and responds.
- Characteristics:
- Centralization: The server acts as a central repository for data or services.
- Modularity: Separate roles for clients and servers enhance scalability.
- Communication: Relies on specific protocols like HTTP, FTP, or WebSocket.
Software Design in the Client-Server Model
- Two-Tier Architecture:
- The client interacts directly with the server.
- Example: Traditional database applications.
- Three-Tier Architecture:
- Introduces a middle layer (application server) to process business logic.
- Example: Web applications with a frontend, backend, and database layer.
- Microservices:
- Divides the server-side application into smaller, independently deployable services.
- Example: Cloud-native applications.
- RESTful and RPC-based Design:
- REST (Representational State Transfer) enables stateless communication via HTTP.
- RPC (Remote Procedure Call) allows direct invocation of procedures on a remote server.
Advantages of the Client-Server Model:
- Centralized control and security.
- Easier maintenance and scalability.
- Efficient resource utilization.
Challenges:
- Network Latency: Slow communication due to network delays.
- Scalability: Handling increased client requests.
- Reliability: Server downtimes can affect all clients.
By mastering these concepts, developers can design efficient and secure network-based applications tailored to diverse real-world needs.
Unit 2. Internet Addresses : 2 hrs
Internet Addresses (2 Hours)
Understanding internet addresses is foundational in network programming. Internet addresses represent devices in a network and play a key role in communication between these devices. This section focuses on classes and methods in Java that handle internet addresses, the differences between IPv4 and IPv6, and practical applications.
2.1 The InetAddress Class: Creating New InetAddress Objects, Getter Methods
Overview of InetAddress
The InetAddress class in Java provides a representation of an IP address and domain name mapping. It acts as a gateway for identifying and resolving internet addresses.
Creating New InetAddress Objects
-
Using Factory Methods:
InetAddress.getByName(String hostName): Resolves a hostname to anInetAddressobject.InetAddress address = InetAddress.getByName("www.example.com");InetAddress.getByAddress(byte[] addr): Creates anInetAddressobject from a byte array.byte[] ip = {127, 0, 0, 1}; InetAddress address = InetAddress.getByAddress(ip);InetAddress.getLocalHost(): Returns the local machine's address.
-
Multihomed Hosts:
- A single hostname may resolve to multiple IP addresses. Use
InetAddress.getAllByName(String hostName)to retrieve all associated IPs.InetAddress[] addresses = InetAddress.getAllByName("www.example.com");
- A single hostname may resolve to multiple IP addresses. Use
Getter Methods
getHostName(): Retrieves the hostname.getCanonicalHostName(): Fetches the fully qualified domain name (FQDN).getHostAddress(): Returns the textual representation of the IP address.isMulticastAddress(): Checks if the address is multicast.
2.2 Methods, Address Types, Testing Reachability, and Object Methods
Methods
- Testing Connectivity:
isReachable(int timeout): Checks if a remote host is reachable within a specified timeout.InetAddress address = InetAddress.getByName("www.google.com"); boolean reachable = address.isReachable(5000); // 5 seconds timeout
- Equality and Hashing:
equals(Object obj)andhashCode(): Compare twoInetAddressobjects for equality.
Address Types
- Unicast: Represents a single device.
- Multicast: Allows communication with multiple devices simultaneously.
- Anycast: One-to-nearest communication (less common).
Testing Reachability
Reachability testing is crucial for verifying whether a specific IP or domain is accessible.
- Use
isReachable()to test reachability. - Applications include monitoring tools and network health checks.
Object Methods
toString(): Provides a string representation of the address.getAddress(): Returns the raw byte array of the address.
2.3 Inet4Address and Inet6Address
Inet4Address
- Represents IPv4 addresses.
- An IPv4 address consists of four bytes, usually displayed in dot-decimal notation (e.g.,
192.168.1.1). - Uses
Inet4Addressas a subclass ofInetAddress.
Inet6Address
- Represents IPv6 addresses.
- An IPv6 address consists of 128 bits, usually displayed in colon-hexadecimal notation (e.g.,
2001:0db8:85a3:0000:0000:8a2e:0370:7334). - Supports modern networking needs, including more devices and better routing.
- Uses
Inet6Addressas a subclass ofInetAddress.
2.4 The Network Interface Class: Factory Method and Getter Method
Overview of the Network Interface Class
The NetworkInterface class represents a network interface, such as an Ethernet card or Wi-Fi adapter.
Factory Methods
NetworkInterface.getByName(String name): Retrieves the network interface by its name (e.g.,eth0).NetworkInterface.getByInetAddress(InetAddress addr): Retrieves the network interface bound to a specific IP address.NetworkInterface.getNetworkInterfaces(): Returns all available network interfaces on the host.
Getter Methods
getName(): Returns the name of the network interface.getInetAddresses(): Returns an enumeration of IP addresses associated with the interface.isUp(): Checks if the interface is active.supportsMulticast(): Verifies if the interface supports multicast communication.
Example Usage
NetworkInterface ni = NetworkInterface.getByName("eth0");
if (ni != null && ni.isUp()) {
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
System.out.println(addresses.nextElement().getHostAddress());
}
}
2.5 Some Useful Programs: SpamCheck and Processing Web Server Logfiles
SpamCheck
A program that checks if an IP address is listed in a spam database.
- Concept:
- Many spam databases use DNS-based blackhole lists (DNSBL).
- Query the blacklist server with the reversed IP address to check if it is flagged.
- Implementation:
String blackListServer = "spamhaus.org"; InetAddress address = InetAddress.getByName("192.168.1.1"); String reversedIP = reverseIP(address.getHostAddress()); boolean isSpam = InetAddress.getByName(reversedIP + "." + blackListServer).isReachable(5000);
Processing Web Server Logfiles
A program that parses web server logs to extract useful information, such as:
-
Client IP addresses.
-
Requested URLs.
-
Response codes.
-
Implementation:
- Read log files line by line.
- Extract fields using regular expressions.
- Resolve client IP addresses to hostnames using
InetAddress.getByName().
try (BufferedReader reader = new BufferedReader(new FileReader("access.log"))) { String line; while ((line = reader.readLine()) != null) { String ip = extractIPAddress(line); InetAddress address = InetAddress.getByName(ip); System.out.println("Host: " + address.getHostName()); } }
By mastering the InetAddress and NetworkInterface classes, along with practical programs like SpamCheck and log processing, developers can efficiently work with internet addresses and troubleshoot network communication issues.
Unit 3. URLs and URIs : 5 hrs
3. URLs and URIs (5 Hours)
Working with Uniform Resource Identifiers (URIs) and Uniform Resource Locators (URLs) is central to network programming. Java provides robust APIs for handling these identifiers, allowing developers to retrieve resources, work with relative URIs, and interact with server-side applications.
3.1 URIs: URLs and Relative URLs
What is a URI?
A Uniform Resource Identifier (URI) is a string that uniquely identifies a resource on the internet. A URI may be further classified as a URL (Uniform Resource Locator) or a URN (Uniform Resource Name).
What is a URL?
A Uniform Resource Locator (URL) specifies the location of a resource and the protocol for accessing it. It’s a type of URI but always includes the access mechanism (e.g., http, ftp).
Relative URLs
Relative URLs define resources relative to another URL (the base URL). They are useful for linking resources within the same domain.
- Example:
- Base URL:
https://www.example.com/docs/ - Relative URL:
images/photo.jpg - Absolute URL:
https://www.example.com/docs/images/photo.jpg
- Base URL:
3.2 The URL Class
Creating New URLs
The URL class in Java represents URLs and provides constructors for defining them.
- Example:
URL url = new URL("https://www.example.com/docs/resource.html");
Retrieving Data From a URL
To fetch data from a URL, use methods such as openStream() or HttpURLConnection.
- Example:
URL url = new URL("https://www.example.com"); try (InputStream input = url.openStream()) { Scanner scanner = new Scanner(input); while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } }
Splitting a URL into Pieces
Methods to extract parts of a URL:
getProtocol(): Returns the protocol (e.g.,https).getHost(): Returns the domain name or IP.getPort(): Returns the port number, or-1if not specified.getPath(): Returns the resource path.getQuery(): Returns the query string.
Equality and Comparison
Two URLs are equal if their protocol, host, port, and file path are identical.
- Use
equals()to compare URLs. - Use
toURI()for fine-grained comparison.
Conversion
A URL can be converted into a URI using toURI().
- Example:
URL url = new URL("https://www.example.com"); URI uri = url.toURI();
3.3 The URI Class
Constructing a URI
The URI class provides constructors for defining URIs, including relative and absolute URIs.
- Example:
URI uri = new URI("https", "www.example.com", "/docs/resource.html", "query=value", "fragment");
Parts of a URI
A URI has the following components:
- Scheme (e.g.,
http,https) - Authority (e.g.,
www.example.com) - Path (e.g.,
/docs/resource.html) - Query (e.g.,
?query=value) - Fragment (e.g.,
#section)
Resolving Relative URIs
Relative URIs are resolved against a base URI using the resolve() method.
- Example:
URI baseUri = new URI("https://www.example.com/docs/"); URI relativeUri = new URI("resource.html"); URI resolvedUri = baseUri.resolve(relativeUri);
Equality and Comparison
URIs are compared using equals() for equality or compareTo() for ordering.
String Representation
Use toString() or toASCIIString() to obtain a string representation of the URI.
3.4 x-www-form-urlencoded: URL Encoder and URL Decoder
Encoding and Decoding
When transmitting data over a URL, special characters must be encoded.
-
URL Encoding: Replaces special characters with
%followed by their hexadecimal value.- Space (
) →%20 - Ampersand (
&) →%26
- Space (
-
Java Classes:
URLEncoder: Encodes a string.URLDecoder: Decodes a string.
-
Example:
String encoded = URLEncoder.encode("name=John Doe&age=30", StandardCharsets.UTF_8); String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
3.5 Proxies: System Properties, The ProxyClass, and The ProxySelector Class
Using Proxies
Proxies act as intermediaries between clients and servers.
System Properties
Set proxy properties using System.setProperty.
- Example:
System.setProperty("http.proxyHost", "proxy.example.com"); System.setProperty("http.proxyPort", "8080");
ProxyClass
The Proxy class allows manual proxy configuration.
- Example:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080)); URL url = new URL("https://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
ProxySelector Class
The ProxySelector class manages proxies dynamically.
- Example:
ProxySelector.setDefault(new CustomProxySelector());
3.6 Communicating with Server-Side Programs Through GET
Use the HttpURLConnection class to send GET requests.
- Example:
URL url = new URL("https://www.example.com/api/data?key=value"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); try (InputStream input = connection.getInputStream()) { Scanner scanner = new Scanner(input); while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } }
3.7 Accessing Password-Protected Sites
Authenticator Class
The Authenticator class handles password-protected resources.
- Set a default authenticator using
Authenticator.setDefault().
PasswordAuthentication Class
Stores credentials securely.
- Example:
Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password".toCharArray()); } });
JPasswordField Class
For GUI-based password input, use JPasswordField.
- Example:
JPasswordField passwordField = new JPasswordField(); String password = new String(passwordField.getPassword());
Conclusion
This section provides a comprehensive understanding of working with URIs, URLs, encoding/decoding, and interacting with proxies or secure resources. Mastering these concepts is crucial for creating networked applications that interact seamlessly with web resources and servers.
Unit 4. HTTP : 2 hrs
4. HTTP (2 Hours)
The Hypertext Transfer Protocol (HTTP) is the foundation of data communication on the web. It is a request-response protocol used by web clients and servers. Understanding HTTP methods, request bodies, and cookie management is critical for implementing effective networked applications.
4.1 The Protocol: Keep-Alive
HTTP and Connections
HTTP operates over a TCP connection, allowing reliable, ordered, and error-checked delivery of data. Traditionally, HTTP/1.0 would close the connection after each request, making multiple requests inefficient.
Keep-Alive in HTTP
The Keep-Alive mechanism allows a single TCP connection to remain open for multiple HTTP requests and responses, reducing the overhead of repeatedly opening and closing connections.
- Benefits:
- Reduces latency by avoiding the need to establish a new connection.
- Enhances performance for web pages with multiple resources (e.g., images, CSS, JS files).
Enabling Keep-Alive
- The
Connection: keep-aliveheader is sent by the client to indicate a desire to reuse the connection. - Example header:
Connection: keep-alive
Keep-Alive Configuration
Many web servers (e.g., Apache, NGINX) allow configuration of Keep-Alive settings, such as:
- Timeout: Duration to keep the connection open.
- Max Requests: The maximum number of requests allowed on a single connection.
4.2 HTTP Methods
HTTP methods define the type of action a client requests from the server. The most commonly used methods include:
GET
- Retrieves data from the server.
- Request parameters are sent in the URL's query string.
- Example:
GET /resource?key=value HTTP/1.1
POST
- Submits data to the server (e.g., form submission).
- Data is sent in the request body.
- Example:
POST /submit HTTP/1.1 Content-Type: application/x-www-form-urlencoded name=John&age=30
PUT
- Updates or replaces a resource on the server.
- Similar to
POSTbut idempotent (repeated requests yield the same result). - Example:
PUT /resource/123 HTTP/1.1
DELETE
- Deletes a resource on the server.
- Example:
DELETE /resource/123 HTTP/1.1
Other Methods
- HEAD: Retrieves headers only, without the body.
- OPTIONS: Queries the server for supported HTTP methods.
- PATCH: Partially updates a resource.
4.3 The Request Body
What is the Request Body?
The request body contains the data sent to the server, often used with methods like POST, PUT, and PATCH.
Common Formats
- Form data:
application/x-www-form-urlencoded- Data is encoded as key-value pairs.
- JSON:
application/json- Widely used for APIs due to its simplicity and readability.
- Multipart/Form-Data:
multipart/form-data- Used for file uploads.
Setting the Request Body in Java
In Java, use the HttpURLConnection class or libraries like Apache HttpClient to send a request with a body.
Example: Sending JSON data with POST.
URL url = new URL("https://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
String jsonInput = "{\"name\":\"John\", \"age\":30}";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInput.getBytes("utf-8");
os.write(input, 0, input.length);
}
4.4 Cookies: CookieManager and CookieStore
What are Cookies?
Cookies are small pieces of data stored on the client’s machine by a web server. They are used for:
- Session management (e.g., maintaining login state).
- Personalization (e.g., saving user preferences).
- Tracking (e.g., analytics).
Cookie Management in Java
The java.net package provides CookieManager and CookieStore for handling cookies.
CookieManager
The CookieManager class manages the storage and retrieval of cookies.
- Setting a global
CookieManager:CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager);
CookieStore
The CookieStore interface is used by CookieManager to maintain cookies. It provides methods like:
add(): Adds a new cookie.get(): Retrieves stored cookies.
Example: Accessing Cookies
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
// Sending a request
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.getResponseCode(); // Triggers cookie storage
// Accessing stored cookies
CookieStore store = cookieManager.getCookieStore();
List<HttpCookie> cookies = store.getCookies();
for (HttpCookie cookie : cookies) {
System.out.println("Cookie: " + cookie);
}
Cookie Policies
Control cookie behavior using CookiePolicy.
- ACCEPT_ALL: Accepts all cookies.
- ACCEPT_NONE: Rejects all cookies.
- ACCEPT_ORIGINAL_SERVER: Accepts cookies only from the original server.
Example: Setting a custom policy
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
Conclusion
HTTP is the backbone of web communication. Understanding its methods, connection management (Keep-Alive), handling request bodies, and managing cookies equips developers to create efficient, secure, and user-friendly web applications. By leveraging Java’s HttpURLConnection, CookieManager, and other tools, developers can build robust client-server systems.
Unit 5. URL Connections : 5 hrs
5. URL Connections (5 Hours)
The URLConnection class in Java is a flexible API for handling communication between a client and a server. It allows applications to retrieve data, configure connections, manage headers, and handle caching and security.
5.1 Opening URLConnections
Establishing a Connection
To open a URLConnection, use the URL class to create a URL object, and then invoke the openConnection() method.
Example:
URL url = new URL("https://example.com");
URLConnection connection = url.openConnection();
connection.connect();
Connection Lifecycle
- Create a
URLobject. - Call
openConnection()to create a connection object. - Configure the connection (e.g., set timeouts, headers).
- Establish the connection with
connect(). - Read or write data.
5.2 Reading Data from Server
InputStream
Data from the server can be read using the InputStream of the URLConnection.
Example:
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
Character Encoding
Ensure correct encoding when reading data using InputStreamReader and specifying the encoding (e.g., UTF-8).
5.3 Reading Headers
Header Fields
Headers provide metadata about the response, such as content type, length, and server information.
Retrieving Specific Header Fields
Use getHeaderField(String name) to retrieve specific header values.
Example:
String contentType = connection.getHeaderField("Content-Type");
System.out.println("Content-Type: " + contentType);
Retrieving Arbitrary Header Fields
Iterate through header fields using getHeaderFieldKey() and getHeaderField().
Example:
int i = 0;
String headerKey;
while ((headerKey = connection.getHeaderFieldKey(i)) != null) {
System.out.println(headerKey + ": " + connection.getHeaderField(i));
i++;
}
5.4 Cache: Web Cache for Java
Caching Overview
Caching stores previously fetched data to reduce server load and improve performance.
Java Web Cache
Java provides a built-in caching mechanism via ResponseCache.
- Use
ResponseCacheto create a custom caching implementation. - Set the cache globally with
ResponseCache.setDefault().
Example:
ResponseCache cache = new CustomCacheImplementation();
ResponseCache.setDefault(cache);
5.5 Configuring the Connection
URLConnection allows several configurations:
Protected Fields
protected URL url: The URL for the connection.protected boolean connected: Indicates if the connection is established.protected boolean allowUserInteraction: Determines if user interaction is allowed.protected boolean doInput: Specifies whether input is expected.protected boolean doOutput: Specifies whether output is allowed.protected boolean useCaches: Indicates if caching is enabled.protected int ifModificationSince: Time for conditional GET requests.protected int timeout: Time limits for the connection.
Timeouts
Set timeouts using:
setConnectTimeout(int timeout)setReadTimeout(int timeout)
Example:
connection.setConnectTimeout(5000); // 5 seconds
connection.setReadTimeout(10000); // 10 seconds
5.6 Configuring the Client Request HTTP Header
Modify request headers using setRequestProperty(String key, String value).
Example:
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept", "application/json");
5.7 Security Considerations for URLConnections
Authentication
Use the Authenticator class to handle HTTP Basic Authentication.
Example:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password".toCharArray());
}
});
HTTPS
For HTTPS connections, ensure SSL/TLS is properly configured using HttpsURLConnection.
Preventing Injection Attacks
- Sanitize inputs before including them in URLs.
- Avoid passing sensitive data in the URL query string.
5.8 Guessing MIME Media Types
MIME Type Detection
MIME types identify the type of content being exchanged. Use URLConnection.guessContentTypeFromStream() or URLConnection.guessContentTypeFromName().
Example:
String mimeType = URLConnection.guessContentTypeFromName("example.pdf");
System.out.println("MIME Type: " + mimeType);
5.9 HttpURLConnection
HttpURLConnection extends URLConnection for handling HTTP-specific features.
The Request Methods
Use methods like GET, POST, PUT, and DELETE.
- Set the method with
setRequestMethod(String method).
Example:
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("POST");
Disconnecting from the Server
Release resources by calling disconnect().
Example:
httpConnection.disconnect();
Handling Server Responses
Read the response code and message using:
getResponseCode()getResponseMessage()
Example:
int responseCode = httpConnection.getResponseCode();
System.out.println("Response Code: " + responseCode);
Proxies
Specify a proxy using the Proxy class.
Example:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(proxy);
Streaming Mode
For large data, enable streaming mode with:
setChunkedStreamingMode(int chunkSize)setFixedLengthStreamingMode(int contentLength)
Example:
httpConnection.setChunkedStreamingMode(1024); // 1 KB chunks
Conclusion
The URLConnection and its subclass HttpURLConnection provide powerful capabilities for network communication. With configurations for headers, caching, security, and proxies, developers can create robust and efficient web applications. Proper understanding and use of these features ensure high performance and secure connections.
Unit 6. Socket for Clients : 5 hrs
6. Sockets for Clients (5 Hours)
Sockets are the foundation of network programming, allowing clients and servers to communicate over TCP/IP. This module explores the concepts, usage, and advanced configurations of sockets, focusing on client-side programming.
6.1 Introduction to Sockets
A socket is an endpoint for sending or receiving data over a network. It represents a bidirectional communication link between a client and a server.
-
Types of Sockets:
- TCP Sockets: Reliable, connection-oriented communication.
- UDP Sockets: Unreliable, connectionless communication.
-
Basic Concepts:
- IP Address: Identifies the device on the network.
- Port Number: Identifies the application or service.
Example: Creating a simple socket
Socket socket = new Socket("example.com", 80); // Connects to a server on port 80
6.2 Using Sockets
Investigating Protocols with Telnet
Telnet is a tool for testing and debugging protocols by establishing raw connections to servers.
Example:
telnet example.com 80
Commands like GET / HTTP/1.1 can then be manually entered to interact with the server.
Reading from Servers with Sockets
Use the socket's InputStream to read data from the server.
Example:
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String response;
while ((response = reader.readLine()) != null) {
System.out.println(response);
}
Writing to Servers with Sockets
Use the socket's OutputStream to send data.
Example:
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("GET / HTTP/1.1");
writer.println("Host: example.com");
writer.println();
6.3 Constructing and Connecting Sockets
Basic Constructors
Create a socket and immediately connect it to a server.
Example:
Socket socket = new Socket("example.com", 80);
Picking a Local Interface to Connect From
Bind the socket to a specific local address and port.
Example:
InetAddress localAddress = InetAddress.getByName("192.168.1.100");
Socket socket = new Socket("example.com", 80, localAddress, 0);
Constructing Without Connecting
Create an unconnected socket for later use.
Example:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("example.com", 80));
Socket Addresses and Proxy Servers
Use SocketAddress to specify endpoints, and configure proxy servers using the Proxy class.
Example:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
Socket socket = new Socket(proxy);
socket.connect(new InetSocketAddress("example.com", 80));
6.4 Getting Information about a Socket
Closed or Connected?
- Check if closed:
isClosed() - Check if connected:
isConnected()
Example:
if (socket.isConnected()) {
System.out.println("Socket is connected");
}
toString()
The toString() method returns a string describing the socket, including the remote and local addresses.
Example:
System.out.println(socket.toString());
6.5 Setting Socket Options
Socket options allow fine-tuning of behavior and performance.
TCP_NODELAY
Disables Nagle's algorithm to send packets immediately.
socket.setTcpNoDelay(true);
SO_LINGER
Specifies how long to wait for unsent data when closing the socket.
socket.setSoLinger(true, 5); // Wait 5 seconds
SO_TIMEOUT
Sets a timeout for blocking socket operations (e.g., reading).
socket.setSoTimeout(10000); // 10 seconds
SO_RCVBUF and SO_SNDBUF
Sets buffer sizes for incoming and outgoing data.
socket.setReceiveBufferSize(8192);
socket.setSendBufferSize(8192);
SO_KEEPALIVE
Keeps the connection alive by sending periodic probes.
socket.setKeepAlive(true);
OOBINLINE
Handles out-of-band data inline.
socket.setOOBInline(true);
SO_REUSEADDR
Allows reuse of the same address by multiple sockets.
socket.setReuseAddress(true);
IP_TOS
Sets the Type of Service (ToS) field for Quality of Service (QoS) settings.
socket.setTrafficClass(0x10); // Low delay
6.6 Socket in GUI Applications
Who Is?
A GUI-based application to query the "whois" database for domain registration information using sockets.
Example Code:
Socket socket = new Socket("whois.iana.org", 43);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("example.com");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response;
while ((response = in.readLine()) != null) {
System.out.println(response);
}
A Network Client Library
Reusable libraries for handling socket connections simplify GUI development. Key features include:
- Connection pooling
- Error handling
- Thread management
Conclusion
Understanding and effectively using sockets is crucial for building robust networked applications. By mastering socket construction, configuration, and data handling, developers can implement efficient communication between clients and servers. Additionally, integrating sockets into GUI applications enables the creation of user-friendly network tools.
Unit 7. Socket for Servers : 5 hrs
7. Socket for Servers (5 Hours)
Server-side sockets are essential for creating networked applications that handle incoming client connections. This section delves into the creation, configuration, and usage of server sockets, focusing on multi-client handling, logging, and HTTP server design.
7.1 Using Server Sockets
A server socket listens for incoming connections from clients. Once a connection is established, it creates a separate socket for communication with the client.
Serving Binary Data
Server sockets can send and receive binary data, enabling file transfer and other binary communication.
Example: Sending binary data
ServerSocket serverSocket = new ServerSocket(5000);
Socket clientSocket = serverSocket.accept();
OutputStream out = clientSocket.getOutputStream();
byte[] data = {0x01, 0x02, 0x03};
out.write(data);
Multithreaded Servers
Multithreading allows handling multiple client connections simultaneously by creating a new thread for each connection.
Example: Multithreaded server
ExecutorService pool = Executors.newFixedThreadPool(10);
ServerSocket serverSocket = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSocket.accept();
pool.execute(() -> handleClient(clientSocket));
}
void handleClient(Socket socket) {
try (InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream()) {
// Handle client communication
} catch (IOException e) {
e.printStackTrace();
}
}
Writing to Servers with Sockets
The server writes responses back to the client using the OutputStream.
Closing Server Sockets
Always close server sockets gracefully to release resources.
Example:
serverSocket.close();
7.2 Logging
What to Log
- Client Information: IP address, port, and connection time.
- Server Events: Startup, shutdown, and errors.
- Requests: URLs, headers, and body for HTTP servers.
- Performance Metrics: Response times, number of connections.
How to Log
Use logging libraries like java.util.logging, Log4j, or SLF4J.
Example:
Logger logger = Logger.getLogger("ServerLogs");
logger.info("Client connected: " + clientSocket.getInetAddress());
7.3 Constructing Server Sockets
Constructing Without Binding
Create a server socket without binding to a specific port, allowing dynamic assignment.
Example:
ServerSocket serverSocket = new ServerSocket(0); // Dynamic port
System.out.println("Listening on port: " + serverSocket.getLocalPort());
7.4 Getting Information about Server Sockets
Retrieve metadata about the server socket, such as the port it is bound to or its local address.
Example:
System.out.println("Local port: " + serverSocket.getLocalPort());
System.out.println("InetAddress: " + serverSocket.getInetAddress());
7.5 Socket Options
Configure server socket behavior using various options.
SO_TIMEOUT
Set a timeout for accepting client connections.
serverSocket.setSoTimeout(10000); // 10 seconds
SO_REUSEADDR
Allow multiple sockets to bind to the same address and port.
serverSocket.setReuseAddress(true);
SO_RCVBUF
Set the size of the buffer for incoming data.
serverSocket.setReceiveBufferSize(8192); // 8 KB
Class of Service
Set the Quality of Service (QoS) for traffic.
serverSocket.setTrafficClass(0x10); // Low delay
7.6 HTTP Servers
A Single File Server
Serve a single file in response to client requests.
Example:
try (ServerSocket serverSocket = new ServerSocket(8080)) {
while (true) {
Socket client = serverSocket.accept();
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/plain");
out.println();
out.println("Hello, World!");
}
}
A Redirector
Redirect clients to a different URL.
Example:
out.println("HTTP/1.1 301 Moved Permanently");
out.println("Location: https://example.com");
out.println();
A Full-Fledged HTTP Server
Implement a basic HTTP server capable of handling GET and POST requests.
Example:
while (true) {
Socket client = serverSocket.accept();
new Thread(() -> {
try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
String line;
while ((line = in.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
}
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println();
out.println("<html><body><h1>Hello, Client!</h1></body></html>");
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
Conclusion
Server-side sockets form the backbone of network programming, enabling scalable and efficient communication with multiple clients. By understanding server socket configuration, logging best practices, and HTTP server implementation, developers can create robust server applications that meet various requirements.
Unit 8. Secure Socket : 4 hrs
8. Secure Socket (4 Hours)
Secure Sockets Layer (SSL) and its successor, Transport Layer Security (TLS), provide secure communication over a network. By encrypting data and ensuring authentication, secure sockets enable confidentiality and integrity in network interactions.
8.1 Secure Communication
Secure communication ensures that data transmitted between a client and server is encrypted, authenticated, and tamper-proof. The JSSE (Java Secure Socket Extension) API in Java provides the tools to implement SSL/TLS.
- Encryption: Prevents eavesdropping.
- Authentication: Verifies the identity of the communicating parties.
- Data Integrity: Ensures that data isn't altered during transit.
8.2 Creating Secure Client Sockets
A secure client socket uses SSL/TLS to connect to a secure server. The SSLSocket class in the javax.net.ssl package facilitates secure communication.
Example: Creating a Secure Client Socket
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try (SSLSocket socket = (SSLSocket) factory.createSocket("www.example.com", 443)) {
socket.startHandshake(); // Initiate SSL handshake
System.out.println("Connected to secure server");
}
8.3 Event Handlers
Event handlers are used to monitor and respond to SSL events such as handshake completion or exceptions during the handshake.
Using HandshakeCompletedListener
This interface listens for handshake completion events.
Example:
socket.addHandshakeCompletedListener(event -> {
System.out.println("Handshake completed with " + event.getSession().getPeerHost());
});
8.4 Session Management
SSLSession
The SSLSession interface manages information about a secure connection.
- Session Resumption: Reuses existing sessions to reduce handshake overhead.
- Retrieving Session Details:
SSLSession session = socket.getSession(); System.out.println("Protocol: " + session.getProtocol()); System.out.println("Cipher Suite: " + session.getCipherSuite());
Session Timeout
Control session duration to balance performance and security:
session.setSessionTimeout(300); // Timeout in seconds
8.5 Client Mode
SSL/TLS supports different operational modes, including client mode and server mode. A secure socket must be explicitly set to client mode if it's designed to initiate connections.
Example:
socket.setUseClientMode(true);
8.6 Creating Secure Server Sockets
A secure server socket listens for and accepts secure client connections. Use the SSLServerSocket class for this purpose.
Example: Creating a Secure Server Socket
SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
try (SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(8443)) {
System.out.println("Secure server is running...");
SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
System.out.println("Secure connection established with client.");
}
8.7 Configure SSL Server Sockets
Secure server sockets can be configured for additional security features.
Choosing the Cipher Suites
Control which cryptographic algorithms are used for secure communication:
serverSocket.setEnabledCipherSuites(new String[]{"TLS_RSA_WITH_AES_256_CBC_SHA"});
Session Management
Configure session timeout and caching for efficiency:
serverSocket.setSessionTimeout(300);
serverSocket.setEnableSessionCreation(true);
Client Mode
Force server sockets to expect client-side authentication (e.g., mutual TLS):
serverSocket.setNeedClientAuth(true); // Requires client certificates
Example: Full Secure Server Implementation
SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
try (SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(8443)) {
System.out.println("Secure server started...");
serverSocket.setEnabledCipherSuites(new String[]{"TLS_AES_128_GCM_SHA256"});
while (true) {
SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
new Thread(() -> {
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String input;
while ((input = in.readLine()) != null) {
System.out.println("Received: " + input);
out.println("Echo: " + input);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
Conclusion
Secure sockets provide robust mechanisms for encrypted, authenticated communication between clients and servers. By understanding SSL/TLS principles, creating secure sockets, and configuring cipher suites, developers can build secure networked applications that safeguard user data and maintain trust.
Unit 9. Nonblocking I/O : 3 hrs
9. Nonblocking I/O (3 Hours)
Nonblocking I/O (Input/Output) is an essential concept for developing scalable, high-performance networked applications. It allows programs to perform I/O operations without being blocked, ensuring that other tasks can continue while waiting for data. Java provides an efficient framework for nonblocking I/O operations via the New I/O (NIO) library, which includes Buffers, Channels, and Selectors.
9.1 An Example Client and Server
Nonblocking I/O allows a server to handle multiple client connections without dedicating a thread to each connection. Here's a simple example of a nonblocking client and server using NIO channels and selectors:
Nonblocking Server Example:
import java.io.IOException;
import java.nio.channels.*;
import java.nio.*;
import java.net.InetSocketAddress;
public class NonBlockingServer {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false); // Set non-blocking mode
serverChannel.socket().bind(new InetSocketAddress(8080));
Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select(); // Wait for an event to occur
for (SelectionKey key : selector.selectedKeys()) {
if (key.isAcceptable()) {
// Accept a connection and register it for reading
SocketChannel clientChannel = serverChannel.accept();
clientChannel.configureBlocking(false);
clientChannel.register(selector, SelectionKey.OP_READ);
System.out.println("Accepted connection from: " + clientChannel.getRemoteAddress());
} else if (key.isReadable()) {
// Read data from client
SocketChannel clientChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(256);
int bytesRead = clientChannel.read(buffer);
if (bytesRead == -1) {
clientChannel.close(); // End of stream, close the connection
} else {
buffer.flip();
System.out.println("Received: " + new String(buffer.array(), 0, bytesRead));
}
}
}
selector.selectedKeys().clear();
}
}
}
Nonblocking Client Example:
import java.io.IOException;
import java.nio.channels.*;
import java.nio.*;
import java.net.InetSocketAddress;
public class NonBlockingClient {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false); // Non-blocking mode
socketChannel.connect(new InetSocketAddress("localhost", 8080));
while (!socketChannel.finishConnect()) {
System.out.println("Connecting to server...");
}
ByteBuffer buffer = ByteBuffer.wrap("Hello Server".getBytes());
socketChannel.write(buffer); // Send data to server
socketChannel.close();
}
}
9.2 Buffers: Creating Buffers, Filling and Draining, Bulk Methods, Data Conversion, View Buffers, Compacting Buffers, Duplicating Buffers, Slicing Buffers, Marking and Resetting, Object Methods
Buffers are containers for data in NIO. They are used for reading from and writing to channels.
Creating Buffers:
ByteBuffer buffer = ByteBuffer.allocate(1024); // Allocate a byte buffer
Filling and Draining Buffers:
- Filling: Writing data into the buffer.
- Draining: Reading data from the buffer.
buffer.put("Hello".getBytes()); // Fill the buffer with data
buffer.flip(); // Switch buffer from writing to reading mode
Bulk Methods:
- put(): Puts data into the buffer.
- get(): Gets data from the buffer.
- put(byte[] src): Puts an entire byte array into the buffer.
- get(byte[] dst): Gets an entire byte array from the buffer.
Data Conversion:
- Use different types of buffers (e.g.,
CharBuffer,ByteBuffer,IntBuffer) for different data types.
CharBuffer charBuffer = CharBuffer.wrap("Hello");
View Buffers:
A buffer can be viewed as another type of buffer (e.g., from a byte buffer to an int buffer).
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
Compacting Buffers:
After reading from a buffer, compacting allows unread data to shift to the beginning, making space for new data.
buffer.compact();
Duplicating Buffers:
A duplicate buffer shares the same data as the original but has independent positions.
ByteBuffer duplicate = buffer.duplicate();
Slicing Buffers:
A slice is a sub-buffer that shares the data with the original buffer.
ByteBuffer slice = buffer.slice();
Marking and Resetting Buffers:
You can mark a position in the buffer and reset to that position later.
buffer.mark();
buffer.reset();
9.3 Channels: Socket Channel, Server Socket Channel, The Channels Class, Asynchronous Channels, Socket Options
Channels are used to connect to I/O devices and transfer data between them. They are analogous to streams but are more flexible in NIO.
Socket Channel:
SocketChannel is used to connect to a server and transfer data.
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
Server Socket Channel:
ServerSocketChannel listens for incoming connections.
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
Asynchronous Channels:
Asynchronous channels allow non-blocking operations to be executed asynchronously.
AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
channel.connect(new InetSocketAddress("localhost", 8080)).get();
Socket Options:
You can configure socket options such as SO_TIMEOUT, SO_RCVBUF, and SO_SNDBUF:
socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 1024);
9.4 Readiness Selection: The Selector Class, The Selection Key Class
The Selector class allows you to monitor multiple channels for events such as connection readiness, data availability, etc., without blocking. It works with SelectionKeys.
The Selector Class:
A Selector monitors multiple channels for I/O events.
Selector selector = Selector.open();
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_CONNECT);
The Selection Key Class:
A SelectionKey represents the registration of a channel with a selector. It can indicate the interest in specific operations like OP_READ, OP_WRITE, OP_CONNECT, and OP_ACCEPT.
SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
You can use the Selector to select keys that are ready for specific operations:
selector.select(); // Blocks until at least one channel is ready
for (SelectionKey key : selector.selectedKeys()) {
if (key.isReadable()) {
// Handle reading data
}
selector.selectedKeys().clear();
}
Selection Key Operations:
OP_READ: Read operations are ready.OP_WRITE: Write operations are ready.OP_ACCEPT: Accept connections.OP_CONNECT: Connection is complete.
Conclusion
Nonblocking I/O, through channels, selectors, and buffers, enables Java applications to handle multiple connections efficiently, without blocking the thread. By using Selectors, applications can monitor multiple channels, and by leveraging Buffers, they can read/write data effectively in a non-blocking manner. These features are crucial for scalable server-side applications that require high performance and low latency.
Unit 10. UDP : 5 hrs
10. UDP (User Datagram Protocol) (5 Hours)
The User Datagram Protocol (UDP) is a connectionless, lightweight, and fast transport layer protocol used for communication between network devices. Unlike TCP, UDP does not establish a reliable connection before sending data, making it suitable for applications where speed is prioritized over reliability, such as real-time communication, streaming, and gaming.
10.1 UDP Protocol
UDP is a connectionless protocol, meaning it does not establish a connection before sending data. The key characteristics of UDP include:
- No connection establishment: Data is sent directly to the recipient without handshakes.
- Unreliable delivery: UDP does not guarantee delivery, order, or error checking. It simply sends packets and leaves the responsibility of reliability to the application.
- Low overhead: Due to the absence of connection establishment, error checking, and acknowledgment mechanisms, UDP has very low overhead compared to TCP.
- Faster: Because of its simplicity, UDP is faster than TCP, making it suitable for real-time applications like VoIP, online gaming, and streaming.
- Packet-based communication: Data is sent in small packets called datagrams.
UDP Header:
The UDP header is 8 bytes long and includes:
- Source Port (2 bytes): The port number on the sender's machine.
- Destination Port (2 bytes): The port number on the receiver's machine.
- Length (2 bytes): The length of the UDP header and data.
- Checksum (2 bytes): Used for error-checking (optional in IPv4).
10.2 UDP Clients
A UDP client sends data to a specific server without establishing a connection. The data is sent as datagrams to the target IP address and port. The client does not expect an acknowledgment or reply from the server.
Example: UDP Client
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String message = "Hello, UDP Server!";
InetAddress serverAddress = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), serverAddress, 9876);
socket.send(packet); // Send the datagram to the server
socket.close();
}
}
In the example above, the UDP client creates a DatagramSocket, prepares the data as a DatagramPacket, and sends it to the server's address and port.
10.3 UDP Servers
A UDP server listens for incoming datagrams on a specific port. It does not establish a connection but instead waits to receive datagrams from clients.
Example: UDP Server
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9876); // Listen on port 9876
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(packet); // Wait for incoming datagram
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received message: " + message);
}
}
}
Here, the UDP server binds to a port (9876), listens for incoming datagrams, and processes the data from the client.
10.4 The Datagram Packet Class
The DatagramPacket class is used to represent the data that is transmitted over UDP.
Constructor:
DatagramPacket(byte[] buf, int length)
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
- buf: The byte array that holds the data.
- length: The length of the data to send.
- address: The destination address of the packet.
- port: The destination port number.
Get Methods:
getAddress(): Returns the address of the packet's destination.getPort(): Returns the port number of the destination.getData(): Returns the data in the packet.getLength(): Returns the length of the data in the packet.
Setter Methods:
setData(byte[] data): Sets the data for the packet.setLength(int length): Sets the length of the data.setPort(int port): Sets the destination port.setAddress(InetAddress address): Sets the destination address.
10.5 The Datagram Socket Class
The DatagramSocket class is used to send and receive datagrams over the network.
Constructor:
DatagramSocket() throws SocketException
DatagramSocket(int port) throws SocketException
- DatagramSocket(): Creates an unbound socket.
- DatagramSocket(int port): Creates a socket bound to a specific port.
Sending Datagrams:
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
send(DatagramPacket packet): Sends a datagram packet to the specified address and port.
Receiving Datagrams:
DatagramSocket socket = new DatagramSocket();
socket.receive(packet);
receive(DatagramPacket packet): Receives a datagram and stores it in the providedDatagramPacket.
Managing Connections:
While UDP is connectionless, a DatagramSocket can be used for both sending and receiving datagrams. However, unlike TCP, there is no concept of "establishing a connection".
10.6 Socket Options
Socket options are configurations that affect the behavior of the socket, such as timeouts, buffer sizes, and addressing modes.
Common Socket Options:
- SO_TIMEOUT: Specifies the timeout for blocking operations like
receive()orsend().
socket.setSoTimeout(5000); // Set timeout to 5 seconds
- SO_RCVBUF: Sets the size of the receive buffer.
socket.setReceiveBufferSize(8192); // 8 KB buffer
- SO_SNDBUF: Sets the size of the send buffer.
socket.setSendBufferSize(8192); // 8 KB buffer
- SO_REUSEADDR: Allows the socket to reuse a local address.
socket.setReuseAddress(true);
- SO_BROADCAST: Allows the socket to send broadcast messages.
socket.setBroadcast(true);
- IP_TOS: Specifies the Type of Service (ToS) for IP packets.
socket.setOption(StandardSocketOptions.IP_TOS, 0x10); // Example ToS value
10.7 UDP Applications
Simple UDP Client:
A simple UDP client can send messages to a server without the need for connection establishment, making it fast and efficient.
// Client sends a message and closes the socket.
UDP Server:
The server can handle multiple clients, receiving and processing datagrams without maintaining a connection to each client.
// Server receives datagrams and processes them.
UDP Echo Client:
An echo client sends a message to the server and waits for the same message to be echoed back.
// Client sends a message and waits for a response.
10.8 Datagram Channel: Using Datagram Channel
The DatagramChannel class is part of Java NIO and is used for reading and writing datagrams in non-blocking mode.
Creating a Datagram Channel:
DatagramChannel channel = DatagramChannel.open();
channel.connect(new InetSocketAddress("localhost", 9876));
Sending and Receiving with Datagram Channel:
ByteBuffer buffer = ByteBuffer.wrap("Hello".getBytes());
channel.send(buffer, new InetSocketAddress("localhost", 9876)); // Send datagram
ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
channel.receive(receiveBuffer); // Receive datagram
Non-blocking Mode:
You can configure a DatagramChannel to operate in non-blocking mode:
channel.configureBlocking(false);
Advantages of Datagram Channel:
- Non-blocking I/O operations for greater scalability.
- Supports both UDP sending and receiving.
- Simplifies asynchronous communication.
Conclusion
UDP is a lightweight protocol designed for applications where speed is crucial and occasional data loss is tolerable. Java provides a rich API to work with UDP, including DatagramPacket, DatagramSocket, and DatagramChannel classes, making it easy to implement both UDP clients and servers. UDP’s simplicity allows for high-speed communication but requires additional mechanisms in the application layer for handling packet loss and reliability when needed.
Unit 11. IP Multicast : 2 hrs
11. IP Multicast (2 Hours)
IP Multicast is a communication technique that allows a source to send data to multiple recipients simultaneously, but unlike broadcast, it only sends data to devices that are interested in receiving it. This makes it an efficient way to deliver data to multiple recipients without overloading the network with redundant messages.
In contrast to unicast, where a message is sent from one sender to one receiver, multicast allows a message to be sent from one sender to multiple receivers within a group.
11.1 Multicasting: Multicast Address and Groups, Clients and Servers, Routers and Routing
Multicast Address:
- In IP networking, a multicast address is a special address range that is reserved for multicast communication. Multicast addresses fall within the following ranges:
- IPv4 Multicast Addresses: 224.0.0.0 to 239.255.255.255 (Class D).
- IPv6 Multicast Addresses: FF00::/8.
A multicast address is used to identify a group of receivers (clients) that are interested in receiving specific messages. Data sent to a multicast address is delivered to all devices that are members of the corresponding multicast group.
Multicast Groups:
- A multicast group is a collection of receivers (clients) that have expressed interest in receiving a particular multicast stream. Devices can join or leave a multicast group dynamically, depending on their needs.
- Clients use the Internet Group Management Protocol (IGMP) (for IPv4) or Multicast Listener Discovery (MLD) (for IPv6) to join and leave multicast groups. When a client subscribes to a multicast group, it informs routers to forward multicast traffic to its network segment.
Multicast Clients and Servers:
- A multicast server sends data to a multicast group, which is addressed to a specific multicast IP address. The server does not know who the receivers are or how many there are—just that they have subscribed to the group.
- A multicast client is a device that subscribes to a multicast group to receive data from a server. Clients listen to the multicast address and receive data from the server if they are part of the group.
Routers and Routing:
- Multicast routers are responsible for forwarding multicast packets from the source to the correct recipients based on the multicast group address. They use Multicast Routing Protocols, such as:
- Protocol Independent Multicast (PIM): A widely used protocol for managing multicast routing.
- Distance Vector Multicast Routing Protocol (DVMRP): A protocol used to manage the forwarding of multicast packets.
- Multicast Open Shortest Path First (MOSPF): An extension to OSPF that supports multicast.
- Multicast Routing: Routers use multicast routing protocols to determine the most efficient path for delivering multicast data. They use techniques such as Reverse Path Forwarding (RPF) to ensure multicast data is routed correctly and without duplication.
11.2 Working with Multicast Sockets: The Constructor, Communicating with a Group
In Java, multicast sockets are represented by the MulticastSocket class, which provides methods to join and leave multicast groups and send/receive multicast datagrams. A MulticastSocket is an extension of the regular DatagramSocket and allows a program to join a multicast group and communicate with that group.
Creating a MulticastSocket:
The MulticastSocket class is used to create multicast sockets. The constructor is as follows:
MulticastSocket socket = new MulticastSocket();
- By default, the
MulticastSocketis bound to an available port. - You can also create a MulticastSocket with a specified port:
MulticastSocket socket = new MulticastSocket(1234); // Bind the socket to port 1234
This creates a multicast socket and binds it to port 1234, which is used to receive multicast packets.
Joining a Multicast Group:
To communicate with a multicast group, the socket must join the group. This is done using the joinGroup() method:
InetAddress group = InetAddress.getByName("224.0.0.1"); // The multicast group address
socket.joinGroup(group);
- The
joinGroup()method tells the socket to join the specified multicast group. The IP address224.0.0.1is an example of a multicast address. You can specify any valid multicast address.
You can also specify the Network Interface and IP Multicast Time-to-Live (TTL):
NetworkInterface networkInterface = NetworkInterface.getByName("eth0"); // Network interface (e.g., eth0)
socket.joinGroup(new InetSocketAddress(group, 1234), networkInterface);
The joinGroup() method ensures that the socket receives packets destined for the multicast group.
Leaving a Multicast Group:
When you're done receiving data, you can leave the group using the leaveGroup() method:
socket.leaveGroup(group);
This tells the socket to stop listening for packets on the multicast address.
Sending Multicast Messages:
You can send a multicast message using the send() method:
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), group, 1234);
socket.send(packet); // Send the packet to the multicast group
- Here,
messageis the data to be sent,groupis the multicast group address, and1234is the port.
Receiving Multicast Messages:
To receive messages from a multicast group, use the receive() method. The socket must be joined to the group first.
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet); // Receive the packet from the group
String receivedMessage = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received message: " + receivedMessage);
- This code waits for messages from the multicast group and prints them when received.
Setting the Multicast TTL (Time-to-Live):
The TTL determines how far the multicast packets can travel in the network. The default TTL value is 1, meaning the packet is confined to the local network segment. You can increase the TTL to allow packets to traverse multiple network segments.
socket.setTimeToLive(255); // Set TTL to 255 (allows the message to be broadcast across networks)
Closing the Multicast Socket:
When done with the socket, you should close it to release the resources.
socket.close();
Conclusion
IP Multicast is an efficient way to send data from a single source to multiple recipients without overloading the network. Java provides the MulticastSocket class for creating multicast communication in client-server applications. Key features include joining and leaving multicast groups, sending and receiving multicast packets, and configuring settings such as TTL. Multicast is particularly useful for real-time communication applications, media streaming, and large-scale data distribution where the same data needs to be sent to many receivers.
Unit 12. Remote Method Invocation : 2 hrs
12. Remote Method Invocation (RMI) (2 Hours)
Remote Method Invocation (RMI) is a Java-based API that enables communication between objects located on different Java Virtual Machines (JVMs). This allows the execution of methods on objects running remotely in a distributed system. RMI abstracts the complexity of network communication, enabling Java programs to invoke methods on objects across the network as if they were local.
RMI is a fundamental component in building distributed applications where objects need to interact over a network. It uses a client-server model, where the server hosts the remote objects, and clients invoke the remote methods.
12.1 Defining and Implementing RMI Service Interface
The first step in using RMI is to define an interface that declares the methods that will be remotely invoked. This interface must extend java.rmi.Remote, which ensures that it can be used remotely. Each method in the interface must throw a java.rmi.RemoteException, which handles network-related issues during remote communication.
Steps to Define and Implement an RMI Service Interface:
-
Define the Remote Interface: The remote interface defines the methods that can be called remotely. It extends the
Remoteinterface and declares the methods withthrows RemoteException.import java.rmi.Remote; import java.rmi.RemoteException; public interface Calculator extends Remote { int add(int a, int b) throws RemoteException; int subtract(int a, int b) throws RemoteException; }Calculatoris the remote service interface.- The methods
addandsubtractare declared to perform basic arithmetic operations and are accessible remotely. - The methods must throw
RemoteExceptionto indicate potential communication failures during remote method invocation.
-
Implement the Remote Interface: The server class implements the
Calculatorinterface, providing concrete implementations for the remote methods.import java.rmi.server.UnicastRemoteObject; import java.rmi.RemoteException; public class CalculatorImpl extends UnicastRemoteObject implements Calculator { public CalculatorImpl() throws RemoteException { super(); } public int add(int a, int b) throws RemoteException { return a + b; } public int subtract(int a, int b) throws RemoteException { return a - b; } }- The class
CalculatorImplextendsUnicastRemoteObjectto make the object exportable to remote clients. - The constructor of
CalculatorImplcallssuper(), which is necessary to export the object for remote access.
- The class
12.2 Creating an RMI Server and Client
Once the remote interface and implementation are defined, the next step is to create the server and client.
RMI Server:
-
Set Up the RMI Registry: The server registers the remote object with the RMI registry. This registry allows clients to look up and find the server's remote object by name.
import java.rmi.Naming; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class RMIServer { public static void main(String[] args) { try { // Start the RMI registry (default port is 1099) Registry registry = LocateRegistry.createRegistry(1099); // Create an instance of the remote object CalculatorImpl calculator = new CalculatorImpl(); // Bind the remote object to the RMI registry Naming.rebind("CalculatorService", calculator); System.out.println("RMI Server is ready."); } catch (Exception e) { System.out.println("Server exception: " + e.getMessage()); e.printStackTrace(); } } }- The
LocateRegistry.createRegistry(1099)method starts the RMI registry on port 1099 (default port for RMI). - The
Naming.rebind("CalculatorService", calculator)binds theCalculatorImplinstance to the RMI registry under the nameCalculatorService.
- The
-
Run the RMI Server: Once the server program is written, it must be executed. This starts the RMI registry and binds the remote object to it. You can run the server like any other Java program:
java RMIServer
RMI Client:
-
Look Up the Remote Object: The client will look up the remote object in the RMI registry using the name provided by the server. The client can then invoke methods on the remote object as if it were local.
import java.rmi.Naming; import java.rmi.RemoteException; public class RMIClient { public static void main(String[] args) { try { // Look up the remote object in the RMI registry Calculator calculator = (Calculator) Naming.lookup("rmi://localhost/CalculatorService"); // Invoke remote methods on the Calculator service int sum = calculator.add(5, 3); int difference = calculator.subtract(9, 4); // Display results System.out.println("Sum: " + sum); System.out.println("Difference: " + difference); } catch (Exception e) { System.out.println("Client exception: " + e.getMessage()); e.printStackTrace(); } } }- The
Naming.lookup("rmi://localhost/CalculatorService")method looks up theCalculatorServiceobject from the RMI registry on the local machine (localhost). - The client then invokes methods on the
calculatorobject as if it were a local object.
- The
-
Run the RMI Client: To run the client, you need to ensure that the RMI server is running and the registry is accessible. Then execute the client code:
java RMIClient
12.3 Running the RMI System
To run an RMI-based system, follow these steps:
-
Start the RMI Registry: Before running the server, the RMI registry must be started. You can do this by running the
rmiregistrytool from the command line (in the directory containing the compiled classes):rmiregistry- This command starts the RMI registry on the default port (1099). It allows the RMI server to register its objects, and clients can look up remote objects using this registry.
-
Compile the Classes: Compile the server, client, and remote interface classes:
javac Calculator.java CalculatorImpl.java RMIServer.java RMIClient.java -
Run the Server: Start the RMI server, which will bind the remote object to the RMI registry:
java RMIServer -
Run the Client: Once the server is running, execute the client:
java RMIClient- The client will connect to the RMI registry, retrieve the remote object, and invoke remote methods.
Conclusion
RMI provides a powerful mechanism for Java-based distributed applications to communicate across different JVMs. By defining remote interfaces, implementing them on the server side, and allowing clients to look up and invoke remote methods, RMI enables seamless communication in a client-server architecture. The key steps involve defining the remote interface, implementing it on the server, binding it to the RMI registry, and ensuring proper communication between the client and the server.
Syllabus
Course Description
Course Description
This course is designed to extend students' knowledge and practice in analysis and design of computer networks by focusing on computer network programming. It includes introduction, Internet Address, URLs and URis, HTTP, URLConnections, Socket Programming, IP Multicast and RMI. The JAVA programming language will be used throughout the course. It does not entirely focus on theoretical concept but also strongly focuses on practical skill based knowledge.
Course objectives
The general objectives of this course are to provide theoretical as well as practical knowledge of network programming to make students capable of developing, implementing, managing and troubleshooting the issues of network programming in their personal as well professional life.
Unit Contents
1. Introduction : 3 hrs
1.1 Network Programing Features and Scope
1.2 Network Programming Language, Tools & Platforms
1.3 Client and Server Applications
1.4 Client server model and software design
2. Internet Addresses : 2 hrs
2.1 The InetAddress Class: Creating New InetAddress Objects, Getter
2.2 Methods, Address Types, Testing Reachability and Object Methods
2.3 Inet4Address and lnet6Address
2.4 The Network Interface Class: Factory Method & Getter Method
2.5 Some Useful Programs: SpamCheck, Processing Web Server Logfiles
3. URLs and URIs : 5 hrs
3.1 URIs: URLs and Relative URLs
3.2 The URL Class: Creating New URLs, Retrieving Data From a URL, Splitting a URL into Pieces, Equality & Comparison and Conversion
3.3 The URI Class: Constructing a URI, The Parts of the URI, Resolving Relative URIs, Equality & Comparison and String Representation
3.4 x-www-form-urlencoded: URL Encoder and URL Decoder
3.5 Proxies: System Properties, The ProxyClass and The ProxySelector Class
3.6 Communicating with Server-Side Programs Through GET
3.7 Accessing Password-Protected Sites: The Authenticator Class, The PasswordAuthentication Class and The JPasswordField Class
4. HTTP : 2 hrs
4.1 The protocol: Keep-Alive
4.2 HTTP Methods
4.3 The Request Body
4.4 Cookies: CookieManager and CookiesStore
5. URL Connections : 5 hrs
5.1 Openning URLConnections
5.2 Reading Data from Server
5.3 Reading Header: Retrieving specific Header Fields and Retrieving Arbitrary Header Fields
5.4 Cache: Web Cache for Java
5.5 Configuring the Connection: protected URL url, protected boolean connected, protected boolean allowUserInteraction, protected boolean dolnput, protected boolean doOutput, protected boolean ifModificationSince, protected boolean useCaches and Timeouts
5.6 Configuring the Client Request HTTP Header
5.7 Security Considerations for URLConnections
5.8 Guessing MIME Media Types
5.9 HttpURLConnection: The Request Methods, Disconnecting from the Server, Handling Server Responses, Proxies and Streaming Mode
6. Socket for Clients : 5 hrs
6.1 Introduction to Socket
6.2 Using Sockets: Investigating Protocols with telnet, Reading from Servers with Sockets, Writing to Servers with Sockets
6.3 Constructing and connecting Sockets: Basic Constructors, Picking a Local Interface to Connect From, Constructing Without Connecting, Socket Addresses and Proxy Servers
6.4 Getting Information about a Socket: Closed or Connected?, toString()
6.5 Setting Socket Options: TCP_NODELAY, SO_LINGER,SO_TIMEOUT, SO_RCVBUF and SO_SNDBUF, SO_ KEEPALIVE, OOBINLINE, SO_REUSEADDER and IP_TOS Class of Services
6.6 Socket in GUI Applications: Who is and A Network Client Library
7. Socket for Servers : 5 hrs
7.1 Using Server Sockets: Serving Binary Data, Multithreaded Servers, Writing to Servers with Sockets and Closing Server Sockets
7.2 Logging: What to Log and How to Log
7.3 Constructing Server Sockets: Constructing Without Binding
7.4 Getting Information about Server Socket
7.5 Socket Options: SO_TIMEOUT, SO_RSUMEADDR, SO_RCVBUF and Class of Service
7.6 HTTP Servers: A Single File Server, A Redirector and A Full-Fledged HTTP Server
8. Secure Socket : 4 hrs
8.1 Secure Communication
8.2 Creating Secure Client Sockets
8.3 Event Handlers
8.4 Session Management
8.5 Client Mode
8.6 Creating Secure Server Socket
8.7 Configure SSL Server Sockets: Choosing the Cipher Suits, Session Management and Client Mode
9. Nonblocking I/O : 3 hrs
9.1 An Example Client and Server
9.2 Buffers: Creating Buffers, Filling and Draining, Bulk Methods, Data Conversion, View Buffers, Compacting Buffers, Duplicating Buffers, Slicing Buffers, Marking and Resetting, Object Methods
9.3 Channels: Socket Channel, Server Socket Channel, The Channels Class, Asynchronous Channels, Socket Options
9.4 Readiness Selection: The Selector Class, The Selection Key Class
10. UDP : 5 hrs
10.1 UDP Protocol
10.2 UDP Clients
10.3 UDP Servers
10.4 The Datagram Packet Class: The Constructor, The get Methods, The setter Methods
10.5 The Datagram Socket Class: The Constructor, Sending and Receiving Datagrams, Managing Connections
10.6 Socket Options: SO_TIMEOUT, SORCVBUF, SO_SNDBUF, SO_ RSUMEADDR, SO_BROADCAST and IP_TOS
10.7 UDP Applications: Simple UDP Clients, UDP Server and A UDP Echo Client
10.8 Datagram Channel: Using Datagram Channel
11. IP Multicast : 2 hrs
11.1 Multicasting: Multicast Address and Groups, Clients and Servers, Routers and Routing
11.2 Working with Multicast Sockets: The Constructor, Communicating with a Group
12. Remote Method Invocation : 2 hrs
12.1 Defining and Implementing RMI Service Interface
12.2 Creating an RMI Server and Client
12.3 Running the RM1 System
Laboratory Work
Laboratory work should be done covering all the topics listed above and a small project work should be carried out using the concept learnt in this course using Java programming Language.
Teaching Methods
The teaching faculties are expected to create environment where students can update and upgrade themselves with the current scenario of computing and information technology with the help of topics listed in the syllabus.
The general teaching pedagogy that can be followed by teaching faculties for this course includes class lectures, laboratory activity, group discussions, case studies, guest lectures, research work, project work, assignments (Theoretical and Practical), and written and verbal examinations.
Text and Reference Books
Reference Books
- Elliotte Rusty Harold, “Java Network Programming”, O’Reilly, 2014.
- Douglas E. Corner, David L. Stevens, “Internetworking with TCP_IP, Vol. III_ Client-Server Programming and Applications, Linux_Posix Sockets Version” Addison-Wesley, 2000.
- David Reilly, Michael Reilly, “Java Network Programming and Distributed Computing”, Addison-Wesley Professional, 2002
- Kenneth L. Calvert, Michael J. Donahoo, “TCP-IP Sockets in Java. Practical Guide for Programmers”, Morgan Kaufmann, 2008.
- Andrew S. Tanenbaum, David J. Wetherall, “Computer Networks, 5/e”, Prentice Hall, 2011
- Kurose, Ross, “Computer Networking: A Top-Down Approach”, Pearson Education Limited, 2017.
No comments:
Post a Comment