Write a program to demonstrate the ProxyClass and the URL URI write a program to construct URI class and
URI write a program to construct URI class and URL class.
ProxySelector Class. import java.net.*; URL is an acronym for Uniform URI is an acronym for Uniform import java.net.*; public class URIandURLDemo { Resource Locator. Resource Identifier. import java.io.*; public static void main(String[] args) { URL is used to describe the URI provides a technique for public class ProxyDemo { // Constructing URI objects identity of an item. defining the identity of an item. public static void main(String[] args) { URI uri1 = URI.create("http://www.example.com"); // Configure the proxy (e.g., using system properties or a custom URL links a web pages, a URL is used to distinguish one URI uri2 = URI.create("https://api.example.com/users/123"); configuration) component of a web page or a resources from other regardless URI uri3 = URI.create("mailto:[email protected]"); System.setProperty("http.proxyHost", "your_proxy_host"); program on a web page with of the method used. // Accessing URI components System.setProperty("http.proxyPort", "your_proxy_port"); the help of accessing methods System.out.println("URI 1 Scheme: " + uri1.getScheme()); // Create a URL object like protocols. System.out.println("URI 1 Host: " + uri1.getHost()); URL url = new URL("http://example.com"); URL provides the details about URI doesn’t the protocol System.out.println("URI 1 Path: " + uri1.getPath()); // Create a ProxySelector and set the proxy what types of protocol is to be specifications. System.out.println("URI 1 Query: " + uri1.getQuery()); ProxySelector selector = ProxySelector.getDefault(); used. System.out.println("URI 1 Fragment: " + uri1.getFragment()); List<Proxy> proxies = selector.select(url.toURI()); URL is a type of URL URI is the superset of URL. // Constructing URL objects if (proxies.size() > 0) { An example of an URL is An example of a URI can be URL url1 = new URL("http://www.example.com"); Proxy proxy = proxies.get(0); https://www.javatpoint.com. ISBN 0-486-35557-4. URL url2 = new URL ("https://api.example.com/users/123 // Use the proxy for network operations The scheme of URL is usually a The URI scheme can be ?param1=value1& param2=value2"); URLConnection connection = url.openConnection(proxy); protocol such as HTTP, HTTPS, protocol, designation, // Accessing URL components // Perform network operations (e.g., read input stream, write FTP, etc. specification, or anything. System.out.println("URL 1 Protocol: " + url1.getProtocol()); output stream) System.out.println("URL 1 Host: " + url1.getHost()); } else { System.out.println("URL 1 Port: " + url1.getPort()); // No proxy found, use direct connection System.out.println("URL 1 Path: " + url1.getPath()); URLConnection connection = url.openConnection(); System.out.println("URL 1 Query: " + url1.getQuery()); // Perform network operations // Converting between URI and URL } } } URL urlFromURI = uri1.toURL(); URI uriFromURL = url1.toURI(); }} what is the use of InetAddress class? what are the types. Explain Define Client Server Model. Write a program to demonstrate Server side What are the HTTP methods? Write a program to print the HTTP header. Inet4address and Inet5Address class with example. and client side connection for chat bot. HTTP Methods List The InetAddress class in Java represents an IP address. It provides The client-server model is a distributed computing architecture where a HTTP (Hypertext Transfer Protocol) defines several methods to interact with web methods for creating, manipulating, and comparing IP addresses. central server provides services to multiple clients. Clients request services resources. Each method has a specific purpose and usage: GET: Retrieves data from a specified resource. It's typically used to request Creating IP addresses from strings or byte arrays. Getting the host from the server, and the server processes the requests and sends back web pages, images, or other data. name associated with an IP address. Getting the IP address associated responses. Example : GET /products HTTP/1.1 with a host name. Comparing IP addresses. Determining if an IP Server Side: Host: www.example.com address is a loopback address or a multicast address. import java.net.*; Accept: application/json Types: IPv4 (Internet Protocol version 4): The older version, using 32 import java.io.*; POST: Submits data to a specified resource, often used to create new resources bits to represent an address. public class ChatbotServer { or update existing ones. Example: IPv6 (Internet Protocol version 6): The newer version, using 128 bits to public static void main(String[] args) throws IOException { POST /products HTTP/1.1 represent an address. ServerSocket serverSocket = new ServerSocket(8080); // Replace 8080 Host: www.example.com Inet4Address with your desired port Content-Type: application/json import java.net.*; System.out.println("Chatbot server listening on port 8080..."); Content-Length: 52 public class Inet4AddressExample { while (true) { {"name": "New Product", "price": 9.99} PUT: Replaces all current representations of a resource with a new one. public static void main(String[] args) { Socket socket = serverSocket.accept(); PATCH: Applies partial updates to a resource. try { System.out.println("Client connected: " + socket.getInetAddress()); DELETE: Removes a specified resource. // Create an IPv4 address from a dotted-decimal string BufferedReader in = new BufferedReader(new Example: DELETE /products/123 HTTP/1.1 InetAddress address = InputStreamReader(socket.getInputStream())); Host: www.example.com InetAddress.getByName("192.168.1.100"); PrintWriter out = new PrintWriter(new HEAD: Similar to GET, but only retrieves the header information of a resource // Check if it's an Inet4Address OutputStreamWriter(socket.getOutputStream()), true); without the body. if (address instanceof Inet4Address) { String inputLine; OPTIONS: Returns the supported methods for a specified resource. Inet4Address inet4Address = (Inet4Address) address; while ((inputLine = in.readLine()) != null) { TRACE: Performs a diagnostic test on the path to a resource. // Get the IPv4 address as a byte array System.out.println("Received from client: " + inputLine); CONNECT: Converts an HTTP connection into a TCP/IP tunnel. byte[] bytes = inet4Address.getAddress(); // Process the input and generate a response (replace with your HTTP 1.1 200 OK // Convert the IPv4 address to a dotted-decimal string chatbot logic) Date: Wed, 11th August 2024 2:00:00 GMT Server: Apache/1.3.4(Unix) PHP/3.0.6 mod_perl/1.17 String dottedDecimal = inet4Address.getHostAddress(); String response = "Hello from the chatbot!"; Last-Modified: Sun,14 August 2024 16:30:00 GMT System.out.println("IPv4 Address: " + dottedDecimal); out.println(response); ETag: “28d907-657-375aa2299” } else { System.out.println("Not an IPv4 address."); } socket.close(); } }} Accept-Ranges: bytes } } catch (UnknownHostException e) { Client Side: Content-Length: 1623 e.printStackTrace(); import java.net.*; Connection : Close } }} import java.io.*; import java.net.*; Inet6Address public class ChatbotClient { import java.util.*; import java.net.*; public static void main(String[] args) throws IOException { public class PrintHttpHeaders { public class Inet6AddressExample { Socket socket = new Socket("localhost", 8080); // Replace "localhost" public static void main(String[] args) throws IOException { public static void main(String[] args) { with the server's IP address if (args.length == 0) { try { System.out.println("Connected to chatbot server"); System.out.println("Usage: java PrintHttpHeaders <URL>"); System.exit(1); } // Create an IPv6 address from a hexadecimal string BufferedReader in = new BufferedReader(new String urlString = args[0]; InetAddress address = InputStreamReader(socket.getInputStream())); URL url = new URL(urlString); InetAddress.getByName("2001:0db8:85a3:0000:0000:8a2e:0370:7334 PrintWriter out = new PrintWriter(new HttpURLConnection connection = (HttpURLConnection) "); OutputStreamWriter(socket.getOutputStream()), true); url.openConnection(); // Check if the address is an IPv6 address Scanner scanner = new Scanner(System.in); connection.setRequestMethod("GET"); if (address instanceof Inet6Address) { while (true) { int responseCode = connection.getResponseCode(); Inet6Address inet6Address = (Inet6Address) address; System.out.print("Enter your message: "); System.out.println("HTTP Response Code: " + responseCode); // Get the IPv6 address as a byte array String message = scanner.nextLine(); Map<String, List<String>> headers = connection.getHeaderFields(); byte[] bytes = inet6Address.getAddress(); out.println(message); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { // Convert the IPv6 address to a hexadecimal string String response = in.readLine(); String headerName = entry.getKey(); String hexString = inet6Address.toString(); System.out.println("Received from chatbot: " + response); } }} List<String> headerValues = entry.getValue(); if (headerName != null) { // Check for null header name System.out.println("IPv6 Address: " + hexString); System.out.print(headerName + ": "); } else { System.out.println("Not an IPv6 address."); for (String headerValue : headerValues) { } } catch (UnknownHostException e) { System.out.print(headerValue + " "); } e.printStackTrace(); System.out.println(); } } } } } } } What is Socket? explain in details about client/socket options write about socket address and proxy servers. what do you know about half closed sockets? Sockets are fundamental to network programming. They represent a A socket address in networking refers to a combination of an IP address and A half-closed socket refers to a state in network communication where communication endpoint between two applications, allowing them to a port number that uniquely identifies a specific socket on a machine. It acts one end of a TCP connection has stopped sending data but can still receive exchange data over a network. Think of a socket as a virtual door that as an endpoint for communication between devices over a network, data from the other end. This is a feature of the Transmission Control connects two programs, enabling them to "talk" to each other. allowing systems to send and receive data to and from each other. Protocol (TCP) that allows for a graceful shutdown of the connection while In Java, socket options can be configured using Key Components of a Socket Address: continuing communication in one direction. the setOption() and getOption() methods of the Socket class (or its 1) IP Address: The IP address is the logical identifier for a network interface. Understanding Half-Closed Sockets: related classes like ServerSocket). Some options can be applied before It can be either an IPv4 address (e.g., 192.168.1.1) or an IPv6 address (e.g., 1) Full Duplex Communication: A typical TCP connection allows data to or after a connection is established. Here's a detailed breakdown of 2001:db8::ff00:42:8329). flow in both directions simultaneously. When both ends are sending and the most commonly used socket options: 2) Port Number: The port number is a 16-bit integer used to identify a receiving data, this is called full-duplex communication. 1) SO_TIMEOUT (Socket Timeout): Sets a timeout for reading data specific process or service on a machine. HTTPS uses port 443. 2) Half-Close: The TCP connection allows either the client or the server to from the input stream. If the timeout expires and no data is read, a 3) Transport Layer Protocol: The socket can be associated with different signal that it is done sending data by sending a FIN (Finish) packet to the SocketTimeoutException is thrown. transport layer protocols like TCP (Transmission Control Protocol) or UDP other side, indicating the half-closure. The connection is still maintained, Eg: socket.setSoTimeout(5000); // Set timeout to 5 seconds (User Datagram Protocol). allowing the other side to continue sending data if needed. int timeout = socket.getSoTimeout(); import java.net.InetAddress; How Half-Closed Sockets Work: 2) SO_LINGER (Linger Option): Controls the linger time for a socket import java.net.InetSocketAddress; 1) Sending a FIN Packet: When one side decides that it has finished when it is closed. If SO_LINGER is enabled, the socket will wait for the public class SocketAddressExample { sending data, it sends a FIN packet to the other side. This action indicates specified amount of time before closing. This gives time to send any public static void main(String[] args) throws Exception { that it won’t send any more data but is still open to receiving data. remaining data. InetAddress ipAddress = InetAddress.getByName("example.com"); 2) Receiving the FIN: The other side receives the FIN packet, indicating Eg: socket.setSoLinger(true, 10); // Enable linger with 10 seconds int port = 80; that the connection is now half-closed. It can still send data to the half- timeout // Create a socket address closed socket but cannot expect to receive any more data from it. boolean isLinger = socket.getSoLinger(); InetSocketAddress socketAddress = new InetSocketAddress(ipAddress, 3) Closing the Other Half: Once the other side finishes sending its data, it 3) SO_REUSEADDR (Reuse Address): Allows a socket to bind to a port port); also sends a FIN packet, fully closing the connection. that was previously used by a socket in the TIME_WAIT state. This // Print the socket address 4) Connection Teardown: After both sides have sent and received FIN option is useful for fast restarts. System.out.println("IP Address: " + socketAddress.getAddress()); packets, the connection is closed in both directions, and no more data can Eg: socket.setReuseAddress(true); // Allow reuse of address System.out.println("Port: " + socketAddress.getPort()); be sent or received. boolean canReuse = socket.getReuseAddress(); }} import java.net.*; 4) SO_RCVBUF (Receive Buffer Size): Sets the size of the receive buffer A proxy server is an intermediary between a client and a server that handles import java.io.*; for the socket, which holds incoming data. The size affects how much requests from the client and forwards them to the appropriate server. Proxy public class HalfClosedSocketExample { data can be buffered before it is processed. servers are often used to improve security, control network traffic, and public static void main(String[] args) throws IOException { Eg : socket.setReceiveBufferSize(1024 * 8); // Set buffer size to 8KB enhance performance in network communication. // Connect to a server int rcvBufSize = socket.getReceiveBufferSize(); Types of Proxy Servers:1) Forward Proxy: A forward proxy is used by clients Socket socket = new Socket("example.com", 80); 5) SO_SNDBUF (Send Buffer Size): Sets the size of the send buffer for to send their requests to a server. The client connects to the proxy, and the // Send data to the server the socket, which holds data to be sent out. This is useful for tuning proxy forwards the request to the destination server. OutputStream outputStream = socket.getOutputStream(); socket performance, especially in high-throughput applications. 2) Reverse Proxy: A reverse proxy is positioned in front of one or more PrintWriter writer = new PrintWriter(outputStream, true); Eg: socket.setSendBufferSize(1024 * 8); // Set send buffer size to 8KB servers and intercepts client requests, routing them to the appropriate writer.println("GET / HTTP/1.1"); int sndBufSize = socket.getSendBufferSize(); server. The client interacts with the proxy, which forwards the request to writer.println("Host: example.com"); 6) SO_KEEPALIVE (Keep-Alive): Enables keep-alive probes for the the server. writer.println(); socket. If enabled, periodic probes are sent to the remote end to 3) Transparent Proxy: A transparent proxy sits between a client and a // Half-close the socket: stop sending data, but keep receiving ensure the connection is still alive. server but operates in a way that is invisible to the client. The client’s traffic socket.shutdownOutput(); Eg: socket.setKeepAlive(true); // Enable keep-alive is intercepted without any configuration changes on the client side. // Read the server's response boolean keepAlive = socket.getKeepAlive(); import java.net.*; InputStream inputStream = socket.getInputStream(); import java.io.*; BufferedReader reader = new BufferedReader(new public class ProxyServerExample { InputStreamReader(inputStream)); public static void main(String[] args) throws IOException { String responseLine; // Define the proxy address and port while ((responseLine = reader.readLine()) != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new System.out.println(responseLine); } InetSocketAddress("proxy.example.com", 8080)); // Fully close the socket // Create a socket and connect through the proxy socket.close(); }} Socket socket = new Socket(proxy); socket.connect(new InetSocketAddress("example.com", 80)); System.out.println("Connected to example.com through proxy."); socket.close(); } } write a program to look for the ports on the local machine by using explain in details about the server socket options What is multithreaded servers? Show with examples server socket objects. Server sockets in Java (and other programming languages) provide several A multithreaded server is a server that can handle multiple client requests Java program that scans ports on the local machine: configuration options that control how they behave in terms of connection concurrently by creating separate threads for each client connection. This PortInUseScanner.java management, timeouts, performance, and security. allows the server to manage multiple clients at the same time, instead of import java.io.IOException; For Server Sockets, Java supports Three options: processing one client request at a time (which is typical of single-threaded import java.net.ServerSocket; 1) SO_TIMEOUT (Socket Timeout): Sets the timeout for how long a server servers). public class PortScanner { socket will wait for a client connection before giving up. This option is Server Code (MultithreadedServer.java) public static void main(String[] args) { crucial in situations where the server might need to wait for a client import java.io.*; int startPort = 1; // Starting port number connection, but you don't want the server to wait indefinitely. import java.net.*; int endPort = 65535; // Ending port number Eg : ServerSocket serverSocket = new ServerSocket(8080); public class MultithreadedServer { System.out.println("Scanning for open ports on the local serverSocket.setSoTimeout(5000); // 5 seconds timeout public static void main(String[] args) { machine..."); try { int port = 8080; for (int port = startPort; port <= endPort; port++) { Socket clientSocket = serverSocket.accept(); // Wait for a connection try (ServerSocket serverSocket = new ServerSocket(port)) { try { } catch (SocketTimeoutException e) { System.out.println("Server listening on port " + port); // Try to bind to the port System.out.println("Connection timed out!"); } while (true) { Socket clientSocket = serverSocket.accept(); ServerSocket serverSocket = new ServerSocket(port); new ClientHandler(clientSocket).start(); // Create new thread for each serverSocket.close(); // Close the socket if binding succeeds 2) SO_REUSEADDR (Reuse Address): Allows a socket to bind to an address client } } catch (IOException e) { e.printStackTrace(); } catch (IOException e) { that is in the TIME_WAIT state. This option is useful when you need to }}} // If we catch an exception, the port is already in use restart a server quickly, and the previous instance of the server hasn't fully class ClientHandler extends Thread { System.out.println("Port " + port + " is in use."); released the port due to TCP's TIME_WAIT state (which can last for several private Socket clientSocket; } } System.out.println("Port scanning completed.");}} minutes). By enabling SO_REUSEADDR, the new instance can bind to the public ClientHandler(Socket socket) { To print both available and in-use ports: same port without waiting for the previous connection to fully close. this.clientSocket = socket; } PortAvailabilityScanner.java Eg: ServerSocket serverSocket = new ServerSocket(); @Override import java.io.IOException; serverSocket.setReuseAddress(true); // Enable reuse of address public void run() { import java.net.ServerSocket; serverSocket.bind(new InetSocketAddress(8080)); try (BufferedReader input = new BufferedReader(new public class PortScanner { InputStreamReader(clientSocket.getInputStream())); public static void main(String[] args) { 3) SO_RCVBUF (Receive Buffer Size): Specifies the size of the buffer used by PrintWriter output = new int startPort = 1; the underlying operating system to store incoming data for a socket. This PrintWriter(clientSocket.getOutputStream(), true)) { int endPort = 1024; // Standard well-known ports option is used to control the amount of memory allocated for receiving String message; System.out.println("Scanning for open ports on the local incoming data before it is passed to the application. Larger buffer sizes can while ((message = input.readLine()) != null) { machine..."); improve throughput in high-bandwidth environments, but they also System.out.println("Client: " + message); for (int port = startPort; port <= endPort; port++) { consume more system memory. output.println("Server: " + message); // Echo back to client try { Eg: ServerSocket serverSocket = new ServerSocket(8080); if ("bye".equalsIgnoreCase(message)) break; // Try to bind to the port serverSocket.setReceiveBufferSize(8192); // 8 KB buffer } } catch (IOException e) { ServerSocket serverSocket = new ServerSocket(port); e.printStackTrace(); serverSocket.close(); // Close the socket if binding succeeds } finally { System.out.println("Port " + port + " is available."); try { clientSocket.close(); } catch (IOException e) { } catch (IOException e) { e.printStackTrace(); } System.out.println("Port " + port + " is in use."); } }} } } System.out.println("Port scanning completed."); }} What is HTTP Server? Write about single-file server and full-fledged HTTP What is JSSE? Explain in context with secure communication? What is session management? How can we get information about the Server. JSSE (Java Secure Socket Extension) is a set of packages in Java that provides session in JSEE? An HTTP server is a software application that listens for and responds to the necessary APIs to enable secure communication over the network using Session management refers to the process of securely handling and HTTP requests from clients (usually web browsers). It serves files like HTML SSL (Secure Sockets Layer) and TLS (Transport Layer Security) protocols. JSSE maintaining the state of interactions between a client (such as a browser) pages, images, stylesheets, JavaScript files, or data from a database in is part of the Java platform and allows developers to build secure network and a server across multiple requests. In a typical web application, HTTP is response to client requests. applications, protecting the integrity and confidentiality of data transmitted a stateless protocol, meaning that each request from a client to a server is Key Functions of an HTTP Server: 1) Listen for Requests: The server listens on a specific port (typically 80 for over insecure networks like the internet. independent, and the server does not inherently maintain information HTTP and 443 for HTTPS) for client requests. Key Concepts of JSSE in Secure Communication: about previous requests. 2) Process Requests: It interprets the incoming HTTP request and decides 1) SSL/TLS Protocols: JSSE implements both SSL and TLS protocols, which Retrieving Session Information in JEE: how to handle it (e.g., fetching a file, generating a dynamic response). are the backbone of secure communication over the internet. These 1) Getting a Session Object: You can retrieve the current session (or 3) Send Responses: The server sends back an HTTP response, which could protocols encrypt the data sent between two endpoints (e.g., a client and a create one if it doesn’t exist) using the HttpServletRequest object: include HTML, JSON, images, or an error code (like 404 for "Not Found"). server), preventing eavesdropping and tampering by attackers. Eg: HttpSession session = request.getSession(); 4) Handle Connections: Modern HTTP servers can handle multiple 2) Encryption: Encryption ensures that data transmitted between two 2) Getting Session Information: Once you have an HttpSession object, you concurrent client connections. parties is unreadable by unauthorized entities. JSSE supports encryption can use it to get various session-related information: 1. Single-File HTTP Server algorithms like AES and RSA, which are used to secure communication Eg: String sessionId = session.getId(); A single-file HTTP server is a basic server that can serve files from a directory, channels. long creationTime = session.getCreationTime(); typically without much configuration. It's often used for development 3) Authentication: JSSE allows both clients and servers to authenticate each long lastAccessedTime = session.getLastAccessedTime(); purposes or small-scale static content hosting. SingleFileHttpServer.java other by exchanging digital certificates. This ensures that the parties int maxInactiveInterval = session.getMaxInactiveInterval(); import java.io.*; involved in the communication are who they claim to be. 3) Setting Session Attributes: Session attributes allow you to store and import java.net.*; 4) Data Integrity: Through message authentication codes (MACs), JSSE retrieve data associated with a particular session. For example, storing public class SingleFileHttpServer { ensures that the data exchanged between client and server has not been user information or other session-specific data. public static void main(String[] args) { tampered with during transit. It provides mechanisms to detect any changes Eg : session.setAttribute("user", "John Doe"); int port = 8080; or corruption in the transmitted data. String user = (String) session.getAttribute("user"); try (ServerSocket serverSocket = new ServerSocket(port)) { 5) Key Management: JSSE uses key stores and trust stores to manage 4) Invalidating a Session: You can invalidate a session (for example, when System.out.println("Server listening on port " + port); cryptographic keys and certificates. The key store contains private keys and a user logs out) using: session.invalidate(); while (true) { certificates used by the application, while the trust store contains trusted Example Servlet with Session Management: Socket clientSocket = serverSocket.accept(); certificates of other entities, such as Certificate Authorities (CAs). import javax.servlet.http.HttpServlet; BufferedReader in = new BufferedReader(new import javax.net.ssl.KeyManagerFactory; import javax.servlet.http.HttpServletRequest; InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), import javax.net.ssl.SSLServerSocketFactory; import javax.servlet.http.HttpServletResponse; true); import javax.net.ssl.SSLServerSocket; import javax.servlet.http.HttpSession; String requestLine = in.readLine(); import javax.net.ssl.SSLSocket; import java.io.IOException; System.out.println("Request: " + requestLine); import java.io.*; public class SessionServlet extends HttpServlet { String response = "HTTP/1.1 200 OK\r\nContent-Type: import java.security.KeyStore; protected void doGet(HttpServletRequest request, HttpServletResponse text/plain\r\n\r\nHello, world!"; public class SimpleSSLServer { response) throws IOException { out.println(response); public static void main(String[] args) throws Exception { HttpSession session = request.getSession(); clientSocket.close(); } } catch (IOException e) // Load the server's keystore if (session.isNew()) { { e.printStackTrace(); } }} KeyStore keyStore = KeyStore.getInstance("JKS"); response.getWriter().println("New session created with ID: " + 2. Full-Fledged HTTP Server try (FileInputStream keyStoreFile = new session.getId()); A full-fledged HTTP server is a more complex and feature-rich server FileInputStream("serverkeystore.jks")) { } else { response.getWriter().println("Existing session with ID: " + designed to handle not only static files but also dynamic content, user authentication, load balancing, and security. keyStore.load(keyStoreFile, "password".toCharArray()); } session.getId()); } FullFledgedHttpServer.java KeyManagerFactory keyManagerFactory = session.setAttribute("user", "John Doe"); import java.io.*; KeyManagerFactory.getInstance("SunX509"); response.getWriter().println("User: " + session.getAttribute("user")); import java.net.*; keyManagerFactory.init(keyStore, "password".toCharArray()); response.getWriter().println("Creation Time: " + public class FullFledgedHttpServer { SSLServerSocketFactory sslServerSocketFactory = session.getCreationTime()); public static void main(String[] args) { (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); response.getWriter().println("Last Accessed Time: " + int port = 8080; SSLServerSocket sslServerSocket = (SSLServerSocket) session.getLastAccessedTime()); try (ServerSocket serverSocket = new ServerSocket(port)) { sslServerSocketFactory.createServerSocket(1234); response.getWriter().println("Session Timeout: " + System.out.println("Server listening on port " + port); System.out.println("SSL Server started, waiting for connections..."); session.getMaxInactiveInterval() + " seconds"); while (true) { while (true) { }} Socket clientSocket = serverSocket.accept(); SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); new Thread(() -> handleClient(clientSocket)).start() } } catch (IOException e) { e.printStackTrace(); }} System.out.println("Client connected!"); private static void handleClient(Socket clientSocket) { BufferedReader in = new BufferedReader(new try (BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream())); InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); true)) { String clientMessage = in.readLine(); String requestLine = in.readLine(); System.out.println("Received from client: " + clientMessage); System.out.println("Request: " + requestLine); out.println("Hello, this is the SSL server!"); if (requestLine != null && requestLine.contains("GET /")) { sslSocket.close(); String response = "HTTP/1.1 200 OK\r\nContent-Type: text/html \r\n\r\n" } }} +"<html><body><h1>Welcome to the Full-Fledged HTTP Server!</h1></body></html>"; out.println(response); } else { String response = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n" + "<html><body><h1>404 Not Found</h1> </body></html>"; out.println(response); } } catch (IOException e) { e.printStackTrace(); } finally { try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }}
Blocking I/O Non-Blocking, I/O
The operation waits until the The operation does not wait; task is complete before it allows other tasks to proceeding. proceed while waiting. Blocks the thread until the The thread continues network operation is execution and handles the finished. operation asynchronously. Common in synchronous Common in asynchronous operations, such as operations, such as InputStream.read() in Java. SocketChannel in NIO or callbacks. Simpler to implement but More complex due to need can lead to potential issues for managing callbacks or with blocking. future objects. Reading data from a socket Using SocketChannel with using socket.read(), select() or poll() for non- inputStream.read(). blocking I/O in Java NIO. Write about the overload createsocket() methods to build a SSL Socket. What should we consider for configuring SSL Server Socket? Explain List down the UDP features and write short notes on DatagramSocket The createSocket() methods are part of the javax.net.ssl.SSLSocketFactory When configuring an SSL Server Socket in Java, you need to consider several critical and DatagramPacket Class class, which is used to create secure sockets for communication over SSL aspects to ensure secure and efficient communication. Configuring an SSL server Features of UDP: (Secure Sockets Layer) or TLS (Transport Layer Security) protocols in Java. The socket involves setting up cryptographic elements like certificates, key stores, and 1) Connectionless: UDP does not require a reliable connection to be SSLSocketFactory class provides several overloaded createSocket() methods, protocols to allow secure connections from SSL/TLS clients. established before data transmission. This makes it more efficient for allowing developers to create SSL sockets with different configurations for 1) Key Store Configuration: A key store contains the server’s private keys and the applications that don't need guaranteed delivery or order of packets. secure communication. certificates needed to authenticate itself to clients. The server uses the private key Common Overloaded createSocket() Methods in SSLSocketFactory: to establish SSL/TLS connections. 2) Datagram-based: UDP transmits data in discrete units called datagrams. 1) createSocket() (No Arguments): Creates an unconnected SSL socket. Once 2) Trust Store Configuration: The trust store contains certificates from trusted Each datagram is independent and can be lost or arrive out of order created, it can be connected later using connect() method, or it can be Certificate Authorities (CAs) that the server uses to validate client certificates (if without affecting other datagrams. configured with additional properties. mutual authentication is enabled). 3) Best-effort delivery: UDP does not guarantee that datagrams will be Eg: SSLSocketFactory factory = (SSLSocketFactory) 3) SSL Protocol Selection: SSL/TLS protocols define the security standards for delivered or that they will arrive in the correct order. If a datagram is lost SSLSocketFactory.getDefault(); communication. The most commonly used protocols are TLS 1.2 and TLS 1.3 (as SSL or corrupted, there is no mechanism to resend it. SSLSocket sslSocket = (SSLSocket) factory.createSocket(); 3.0 and older protocols are considered insecure). 4) Lightweight: UDP has a smaller overhead compared to TCP, making it 2) createSocket(String host, int port) (Connect to a Specific Host and Port): 4) Cipher Suites: A cipher suite is a combination of algorithms used to secure suitable for applications that prioritize speed over reliability. Creates and connects the SSL socket to a specified remote host and port. communication, including key exchange, encryption, and message authentication. 5) No flow control or congestion control: UDP does not implement flow This is the most commonly used form when establishing an SSL connection to 5) Client Authentication (Optional): one way and two way authentication control or congestion control mechanisms, which can lead to network a server. Eg: SSLSocketFactory factory = (SSLSocketFactory) 6) Session Management: SSL/TLS sessions are often reused to avoid the overhead congestion if the sender sends data too quickly. SSLSocketFactory.getDefault(); of renegotiating security parameters for each connection. SSLSocket sslSocket = (SSLSocket) factory.createSocket("example.com", 443); 7) Security Updates and Patches: The cryptographic libraries and protocols used by a) DatagramSocket Class : The DatagramSocket class in Java is used to 3) createSocket(InetAddress address, int port) (Connect to a Specific IP SSL/TLS can have vulnerabilities. create a socket for sending and receiving datagram packets over the Address and Port): Similar to the previous overload, but uses an InetAddress 8) Socket Timeout Configuration: Set timeouts for socket operations to prevent network using UDP. Unlike TCP's Socket, which is connection-oriented, object instead of a string hostname to specify the remote server. Denial of Service (DoS) attacks where clients can tie up server resources by keeping DatagramSocket supports connectionless communication, allowing it to Eg: InetAddress address = InetAddress.getByName("example.com"); sockets open. send and receive packets independently. SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); import javax.net.ssl.*; DatagramSocket: SSLSocket sslSocket = (SSLSocket) factory.createSocket(address, 443); import java.io.*; Creating a socket: The DatagramSocket class is used to create a UDP 4) createSocket(String host, int port, InetAddress localAddr, int localPort) import java.security.KeyStore; socket. It provides methods for sending and receiving datagrams. (Connect to a Host with Local Address and Port Binding): Creates an SSL public class SSLServer { Binding to a port: A DatagramSocket object must be bound to a specific socket, connects it to the specified remote host and port, and binds it to a public static void main(String[] args) throws Exception { port number on the local machine. This allows the socket to receive specified local address and port. KeyStore keyStore = KeyStore.getInstance("JKS"); incoming datagrams addressed to that port. Eg: InetAddress localAddr = InetAddress.getByName("192.168.1.100"); try (FileInputStream keyStoreFile = new FileInputStream("serverkeystore.jks")) SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); { Sending datagrams: The send method of the DatagramSocket class is used SSLSocket sslSocket = (SSLSocket) factory.createSocket("example.com", 443, keyStore.load(keyStoreFile, "password".toCharArray()); } to send a datagram to a specified destination address and port. localAddr, 12345); KeyManagerFactory keyManagerFactory = Receiving datagrams: The receive method of the DatagramSocket class is 5) createSocket(InetAddress address, int port, InetAddress localAddr, int KeyManagerFactory.getInstance("SunX509"); used to receive an incoming datagram. It returns a DatagramPacket object localPort) (Connect to IP Address with Local Binding): Similar to the keyManagerFactory.init(keyStore, "password".toCharArray()); containing the received data and the sender's address. previous overload but accepts an InetAddress for both the remote and local SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); Example of Creating a DatagramSocket: DatagramSocket socket = new addresses instead of a string hostname. sslContext.init(keyManagerFactory.getKeyManagers(), null, null); DatagramSocket(1234); // Binds to port 1234 Eg: InetAddress remoteAddr = InetAddress.getByName("example.com"); SSLServerSocketFactory sslServerSocketFactory = b) DatagramPacket Class:The DatagramPacket class in Java represents a InetAddress localAddr = InetAddress.getByName("192.168.1.100"); sslContext.getServerSocketFactory(); data packet to be sent or received via a DatagramSocket over UDP. A SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLServerSocket sslServerSocket = (SSLServerSocket) datagram packet is a self-contained, independent packet of data that SSLSocket sslSocket = (SSLSocket) factory.createSocket(remoteAddr, 443, sslServerSocketFactory.createServerSocket(8443); carries enough information for the receiver to understand where it localAddr, 12345); sslServerSocket.setEnabledProtocols(new String[] {"TLSv1.2", "TLSv1.3"}); 6) createSocket(Socket socket, String host, int port, boolean autoClose) sslServerSocket.setEnabledCipherSuites(new String[] { originated and what data it contains. (Layer SSL on an Existing Socket): This overload is used to layer SSL/TLS on "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", Holds Data: It contains the actual data to be transmitted as a byte array. top of an existing plain socket. It is useful when upgrading an existing "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" }); Packet Addressing: It includes information about the destination IP connection (like a regular Socket) to an SSL connection after some initial System.out.println("SSL Server started, waiting for connections..."); address and port number for outgoing packets, and it can store the communication (such as a STARTTLS negotiation). while (true) { sender's IP address and port for incoming packets. Eg: Socket plainSocket = new Socket("example.com", 80); SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); Used for Both Sending and Receiving: The same DatagramPacket class is SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); System.out.println("Client connected"); used to send and receive data. For sending, you specify the destination SSLSocket sslSocket = (SSLSocket) factory.createSocket(plainSocket, BufferedReader in = new BufferedReader(new address, and for receiving, the packet will store the sender's information. "example.com", 443, true); InputStreamReader(sslSocket.getInputStream())); Size of Packet: You must specify the length of the packet's data. UDP 7) createSocket(Socket socket, InputStream consumed, boolean autoClose) PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true); datagrams are limited to a size of 65,535 bytes, but most networks limit (SSL Layering with Consumed InputStream): This method allows SSL to be out.println("Hello from SSL Server!"); packet sizes further (often around 1,500 bytes). layered on top of an existing Socket connection where part of the input System.out.println("Received: " + in.readLine()); stream has already been consumed. sslSocket.close(); } }} Example of Creating a DatagramPacket: Eg: InputStream consumedInputStream = socket.getInputStream(); // Assume byte[] data = "Hello".getBytes(); //For Sending part of the stream is read InetAddress address = InetAddress.getByName("192.168.1.1"); SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); DatagramPacket packet = new DatagramPacket(data, data.length, address, SSLSocket sslSocket = (SSLSocket) factory.createSocket(plainSocket, 1234); byte[] buffer = new byte[1024]; // For receiving consumedInputStream, true); DatagramPacket packet = new DatagramPacket(buffer, buffer.length); Discuss RMI architecture with suitable diagram and discuss each layer in the Write a code to create RMI Client and Server to add two numbers and architecture briefly. display the summed up result. Java Remote Method Invocation (RMI) enables an object running in one Java Server.java Virtual Machine (JVM) to invoke methods on an object running in another JVM. import java.rmi.Naming; This mechanism facilitates remote communication between applications and is import java.rmi.registry.LocateRegistry; based on the concept of distributed objects. The RMI architecture is layered to import java.rmi.RemoteException; allow for easy communication, object marshalling/unmarshalling, and transparent method invocation. import java.rmi.server.UnicastRemoteObject; Layers of RMI Architecture interface Adder extends java.rmi.Remote { (Stub/Skeleton Layer, Remote int add(int x, int y) throws RemoteException; } Reference Layer, Transport class AdderRemote extends UnicastRemoteObject implements Adder { Layer) protected AdderRemote() throws RemoteException { 1) Stub/Skeleton Layer: super(); } a) Stub: A local object that @Override represents the remote object public int add(int x, int y) throws RemoteException { on the client side. It acts as a return x + y; } }public class Server { proxy for the remote object, public static void main(String[] args) { try { handling method calls and LocateRegistry.createRegistry(1099); marshalling/ unmarshalling of parameters and return values. b) Skeleton: A local object that represents the remote object on the server side. It System.out.println("RMI registry started."); receives incoming method calls from the stub, unmarshalls the parameters, invokes AdderRemote adder = new AdderRemote(); the actual method on the remote object, and marshals the return value. Naming.rebind("rmi://localhost:1099/AdderService", adder); 2. Remote Reference Layer: This layer manages references to remote objects and System.out.println("AdderService is bound and ready to use."); handles the communication between the stub and the skeleton. It provides } catch (Exception e) { e.printStackTrace(); } } } (Invocation Handling, Reference Management, Garbage Collection) Client.java 3) Transport Layer: Responsible for transmitting data between the client and import java.rmi.Naming; server. Typically uses TCP/IP for reliable, connection-oriented communication. public class Client { Handles tasks like establishing connections, sending and receiving data, and closing public static void main(String[] args) { connections. try { How RMI Architecture Works: Adder stub = (Adder) a) Client-Side: The client invokes a method on the local stub.The stub serializes the method parameters and sends the invocation request to the server over the Naming.lookup("rmi://localhost:1099/AdderService"); transport layer. int result = stub.add(5, 3); b) Server-Side: The request is passed through the transport layer to the skeleton System.out.println("Result of addition: " + result); (or directly to the remote object if skeletons are not used).The skeleton deserializes } catch (Exception e) { the parameters and invokes the actual method on the remote object.The result is e.printStackTrace(); serialized and sent back to the client. } }} c) Return to Client: The client stub receives the response, deserializes the result, and returns the value to the client program. Write a program to create an UDP Server and client with explain with echo what is the procedure for constructing and connecting client socket? explain write short notes on IP multi cast, RMI Services,Secure Server Socket, client/server example with code. client socket option URL Connection and Components in URL. UDP Server: Constructing and connecting a client socket in Java involves creating a socket IP Multicast is a network communication technique that allows a single import java.net.*; object, specifying the server address and port number, and then establishing a data packet to be sent to multiple destinations simultaneously by public class UDPServer { connection to the server. The Socket class in Java provides methods and options for targeting a multicast IP address. Devices that wish to receive the data join public static void main(String[] args) throws SocketException, IOException { this process. the multicast group associated with this address, which helps to conserve DatagramSocket serverSocket = new DatagramSocket(5000); Procedure for Constructing and Connecting a Client Socket byte[] receiveData = new byte[1024]; 1) Import Required Classes: import java.io.*; import java.net.*; bandwidth by avoiding multiple transmissions of the same data. byte[] sendData = new byte[1024]; 2) Create a Socket Object: Use the Socket class to create a socket object. You RMI Services (Remote Method Invocation) in Java allow objects running System.out.println("UDP Server started on port 5000. Waiting for need to specify the server’s address (hostname or IP) and port number to connect in different JVMs to interact as if they were in the same JVM. Through connections..."); to the server. RMI, objects can invoke methods on remote objects, enabling distributed while (true) { 3) Connect to the Server: you can create a socket and then explicitly connect it computing and simplifying the development of network-based DatagramPacket receivePacket = new DatagramPacket(receiveData, using the connect() method. applications. receiveData.length); 4) Communicate with the Server: Once the connection is established, you can use Secure Server Socket refers to a server socket that employs SSL/TLS serverSocket.receive(receivePacket); input and output streams to communicate with the server. protocols to encrypt data exchanged between the client and server, String sentence = new String(receivePacket.getData()); 5) Close the Socket: After communication is complete, close the socket to free up ensuring confidentiality and integrity of the communication. It uses InetAddress IPAddress = receivePacket.getAddress(); resources. SSLServerSocket to provide a secure communication channel over a int port = receivePacket.getPort(); Example Code for Creating and Connecting a Client Socket: network, protecting against eavesdropping and tampering. System.out.println("Received message from " + IPAddress + ":" + port import java.io.*; + ": " + sentence); import java.net.*; URL Connection refers to the process of opening and managing network String capitalizedSentence = sentence.toUpperCase(); public class Client { connections using a URL (Uniform Resource Locator) in Java. This is sendData = capitalizedSentence.getBytes(); public static void main(String[] args) { typically done using the URLConnection class, which provides methods for DatagramPacket sendPacket = new DatagramPacket(sendData, Socket socket = null; interacting with resources identified by URLs. It supports various protocols sendData.length, IPAddress, port); PrintWriter out = null; such as HTTP, HTTPS, FTP, and more. The URLConnection class allows you serverSocket.send(sendPacket); BufferedReader in = null; try { to set request properties, read responses, and handle data streams from } }} String serverAddress = "localhost"; // Server address (hostname or IP) the network. UDP Client: int serverPort = 12345; Components of URL: 1) Protocol: Specifies the communication protocol import java.net.*; socket = new Socket(serverAddress, serverPort); (e.g., http, https, ftp). It defines how data is transferred over the network. public class UDPClient { System.out.println("Connected to server."); Eg: http:// public static void main(String[] args) throws SocketException, out = new PrintWriter(socket.getOutputStream(), true); 2) Host: The domain name or IP address of the server where the resource UnknownHostException, IOException { in = new BufferedReader(new DatagramSocket clientSocket = new DatagramSocket(); InputStreamReader(socket.getInputStream())); is located. Example: example.com byte[] sendData = new byte[1024]; String message = "Hello, Server!"; 3) Port: (Optional) The port number on the server to connect to. If byte[] receiveData = new byte[1024]; out.println(message); omitted, the default port for the protocol is used (e.g., port 80 for HTTP). InetAddress IPAddress = InetAddress.getByName("localhost"); System.out.println("Sent to server: " + message); Example: :8080 int port = 5000; String response = in.readLine(); 4) Path: The specific location of the resource on the server. It typically System.out.print("Enter a message: "); System.out.println("Received from server: " + response); represents a file or directory. Example: /path/to/resource Scanner scanner = new Scanner(System.in); } catch (IOException e) { 5) Query: (Optional) A string of parameters for the resource, often used in String sentence = scanner.nextLine(); e.printStackTrace(); web requests. It starts with ? and is followed by key-value pairs. sendData = sentence.getBytes(); } finally { try { Example: ?key1=value1&key2=value2 DatagramPacket sendPacket = new DatagramPacket(sendData, if (in != null) in.close(); 6) Fragment: (Optional) A fragment identifier used to point to a specific sendData.length, IPAddress, port); if (out != null) out.close(); part of the resource, such as an anchor in an HTML document. It starts clientSocket.send(sendPacket); if (socket != null) socket.close(); DatagramPacket receivePacket = new DatagramPacket(receiveData, } catch (IOException e) { with #. Example: #section1 receiveData.length); e.printStackTrace(); } } } } Example URL: clientSocket.receive(receivePacket); Client Socket Options: http://example.com:8080/path/to/resource?key1=value1&key2=value2#s String modifiedSentence = new String(receivePacket.getData()); 1) Server Address and Port: (Constructor: Socket(String host, int port) specifies the ection1 System.out.println("MODIFIED: " + modifiedSentence); server's address and port.Alternative: Socket(InetAddress address, int port) where clientSocket.close(); }} InetAddress can be used for more detailed IP address handling.) Echo Example: 2) Local Address and Port: Constructor: Socket(String host, int port, InetAddress The provided code demonstrates a simple echo server and client. The server localAddr, int localPort) specifies the server's address and port, and also the local receives messages from the client, capitalizes them, and sends them back. address and port to use. The client sends a message to the server and receives the capitalized 3) Connection Timeout: Method: Socket(SocketAddress endpoint, int timeout) response. allows setting a connection timeout in milliseconds. Eg : socket = new Socket(); Key Points: socket.connect(new InetSocketAddress(serverAddress, serverPort), 5000); UDP is connectionless, meaning no explicit connection setup is required. 4) SO_KEEPALIVE Option: Method: socket.setKeepAlive(true) keeps the Datagrams are sent and received independently. connection alive by periodically sending messages to ensure the connection is still UDP does not guarantee delivery or order of datagrams. active. The example uses a simple echo operation, but you can customize the 5) SO_TIMEOUT Option: Method: socket.setSoTimeout(int timeout) sets a read processing logic to suit your application needs. timeout on the socket, specifying the maximum time to wait for data before Remember to replace "localhost" with the actual IP address of the server if throwing a SocketTimeoutException. you're running them on different machines.