Chapter 5
Network Programming
TU BCA past exam questions
Past questions and answers
50 questions set from this chapter. Most repeated first.
- 2021 · 5 marks
Define Client-Server software model. Explain the features of Java as a Network programming language.
Similar questions: What is the Client-Server software model? Explain (2022)
Answer
Client-Server model
The client-server model is a distributed architecture in which a server program provides a service or resource and one or more client programs request it over a network. The client initiates the communication (sends a request), the server waits, processes the request and sends back a response. Examples: a web browser (client) and a web server, an email client and a mail server.
Features of Java as a network programming language
- Built-in networking API: the
java.netpackage providesSocket,ServerSocket,URL,URLConnection,InetAddress,DatagramSocketand more, so TCP, UDP and HTTP programs are short. - Platform independence: compiled bytecode runs on any JVM, so the same client or server works on different operating systems and hardware.
- Multithreading: built-in threads let a server handle many clients at the same time.
- Stream-based I/O:
java.iostreams andjava.niobuffers and channels make reading and writing network data uniform. - Security: the security manager, bytecode verifier, and SSL/TLS support (JSSE) protect network applications.
- Robustness: strong typing, exception handling and automatic garbage collection reduce crashes and memory leaks.
- Internationalisation: Unicode support lets text be exchanged in many languages.
- Distributed object support: RMI and URL based class loading support distributed applications.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What is the Client-Server software model? Explain the strengths and weaknesses of Java programming as a network programming language.
Similar questions: Define Client-Server software model. Explain the features (2021)
Answer
Client-Server model
In the client-server model, a server program offers a service and waits for requests, while a client program starts the communication, sends a request and uses the response. Many clients can use one server, and the roles are defined per interaction, not per machine. Examples: web browser and web server, FTP, e-mail, database clients.
Strengths of Java for network programming
- A rich, easy
java.netAPI (sockets, URLs, datagrams) andjava.niofor scalable I/O. - Platform independence through bytecode and the JVM.
- Built-in multithreading, so servers can handle many clients concurrently.
- Strong security features: SSL/TLS (JSSE), sandboxing, security manager.
- Robustness: type safety, exceptions, garbage collection, no pointer errors.
- Support for higher-level distributed technologies: RMI, servlets, JMS, web services.
- Unicode and good library support for protocols such as HTTP.
Weaknesses
- Slower than C/C++ because of interpretation and JIT overhead, and higher memory use.
- Higher-level abstractions hide some low-level socket features (for example raw sockets, ICMP and some options are not directly available).
- Blocking stream I/O of
java.netscales poorly, and NIO is more complex. - Garbage collection pauses can affect real-time performance.
- Java-specific technologies such as RMI and serialization are tied to Java, which limits interoperability.
- JVM start-up time and the need for a runtime installed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
What is the use of the NetworkInterface Class? Explain the basic features of the NetworkInterface class.
Answer
Use of the NetworkInterface class
java.net.NetworkInterface represents a network interface of the local machine, such as an Ethernet card (eth0) or the loopback interface (lo). It is used to find out which interfaces and IP addresses a host has, which is needed, for example, to choose the interface for a multicast socket or to bind a server to one specific address.
Basic features
getNetworkInterfaces()returns anEnumerationof all interfaces on the machine.getByName(String name)andgetByInetAddress(InetAddress addr)return a particular interface.getName()andgetDisplayName()give the interface name.getInetAddresses()andgetInterfaceAddresses()list the IP addresses (and prefix length, broadcast address) assigned to it.getHardwareAddress()returns the MAC address as a byte array.isUp(),isLoopback(),isVirtual(),isPointToPoint()andsupportsMulticast()report its state and type.getMTU()returns the maximum transmission unit.getParent()andgetSubInterfaces()give the hierarchy of virtual interfaces.
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
System.out.println(ni.getName() + " up=" + ni.isUp());
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Explain HTTP methods with examples.
Answer
HTTP methods
HTTP (HyperText Transfer Protocol) is a request-response protocol; the method in the request line tells the server what action to perform on the resource.
- GET retrieves a resource. Parameters are placed in the URL; it is safe and idempotent. Example:
GET /index.html HTTP/1.1, orGET /search?q=nepal HTTP/1.1. - POST sends data in the request body to be processed, for example submitting a form or creating a record. It is not idempotent. Example:
POST /loginwith bodyuser=ram&pass=123. - PUT replaces or creates the resource at the given URL with the body content. It is idempotent. Example:
PUT /students/5. - DELETE removes the specified resource. Example:
DELETE /students/5. - HEAD is the same as GET but returns only headers, with no body. It is used to check size, type or last-modified time.
- OPTIONS asks which methods the server supports for a resource.
- PATCH applies a partial modification to a resource.
- TRACE echoes the received request back, for diagnostics. CONNECT opens a tunnel, typically for HTTPS through a proxy.
Example in Java:
URL url = new URL("http://example.com/api");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET"); // or POST, PUT, DELETE, HEAD
System.out.println(c.getResponseCode());
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Write a program to display the socket information [address, port, local address, local port].
Answer
Socket information can be obtained with getInetAddress() (remote address), getPort() (remote port), getLocalAddress() and getLocalPort().
import java.net.*;
public class SocketInfo {
public static void main(String[] args) {
try (Socket s = new Socket("www.google.com", 80)) {
System.out.println("Address : " + s.getInetAddress());
System.out.println("Port : " + s.getPort());
System.out.println("Local address : " + s.getLocalAddress());
System.out.println("Local port : " + s.getLocalPort());
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
Sample output:
Address : www.google.com/142.250.190.4
Port : 80
Local address : /192.168.1.5
Local port : 51234
The remote port is the one given to the constructor, while the local port is chosen automatically by the operating system.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Write a server-side program for a daytime service using socket.
Answer
The Daytime service listens on port 13 (it needs administrator rights on most systems; a higher port such as 1313 can be used for testing). For each client connection the server writes the current date and time and closes the connection.
import java.io.*;
import java.net.*;
import java.util.Date;
public class DaytimeServer {
public static void main(String[] args) throws IOException {
int port = 13;
try (ServerSocket server = new ServerSocket(port)) {
System.out.println("Daytime server running on port " + port);
while (true) {
try (Socket client = server.accept()) {
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println(new Date().toString());
} catch (IOException e) {
System.err.println("Client error: " + e);
}
}
}
}
}
A client such as telnet localhost 13 or a Socket reading one line receives the date and time string.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Define Non-blocking I/O. Differentiate between blocking and non-blocking socket communication in Java.
Answer
Non-blocking I/O
Non-blocking I/O (Java NIO, java.nio) lets a thread start an I/O operation and continue without waiting for it to complete. A single thread can manage many connections using channels (SocketChannel, ServerSocketChannel) in non-blocking mode, buffers (ByteBuffer) and a Selector that reports which channels are ready to read, write or accept.
Blocking versus non-blocking socket communication
| Basis | Blocking (java.net / java.io) | Non-blocking (java.nio) |
|---|---|---|
| Behaviour | accept(), read() and write() wait until the operation completes | Calls return immediately, possibly with no data (0 bytes or null) |
| Threads | Usually one thread per client | One thread handles many clients with a Selector |
| Data handling | Stream oriented | Buffer and channel oriented |
| Scalability | Poor for thousands of clients because of thread overhead | High, suited to busy servers |
| Complexity | Simple to write and understand | More complex, with buffers and readiness handling |
| Setup | Socket, ServerSocket | channel.configureBlocking(false), Selector, SelectionKey |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Write Short Notes on (Any Two):
a) Secure Communication
b) Multicast Sockets
c) RMI Server
Answer
(a) Secure Communication
Data sent over a network can be read or altered by attackers, so sensitive traffic must be protected. Secure communication aims at confidentiality (encryption), integrity (message digests, MACs) and authentication (certificates, digital signatures). In Java the JSSE (Java Secure Socket Extension) package javax.net.ssl provides SSL/TLS: SSLSocketFactory and SSLServerSocketFactory create SSLSocket and SSLServerSocket, which are used like ordinary sockets but with the handshake, key exchange and encryption handled automatically. Certificates are kept in keystores and truststores.
SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket s = (SSLSocket) f.createSocket("example.com", 443);
(b) Multicast Sockets
Multicast sends one datagram to a group of interested hosts instead of one copy per receiver, which saves bandwidth. Hosts join a group identified by a class D IP address (224.0.0.0 to 239.255.255.255). In Java, MulticastSocket (a subclass of DatagramSocket) is used: joinGroup(InetAddress) to join, leaveGroup() to leave, setTimeToLive() to limit how far packets travel. Uses include video conferencing, stock tickers and online games.
MulticastSocket ms = new MulticastSocket(4446);
ms.joinGroup(InetAddress.getByName("230.0.0.1"));
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
What is the procedure for constructing and connecting Server sockets? Explain the Server Socket options with examples.
Answer
Constructing and connecting a server socket
A ServerSocket (in java.net) listens on a port for incoming TCP connections.
Constructors:
ServerSocket()creates an unbound socket, to be bound later.ServerSocket(int port)binds to the port (0 chooses any free port).ServerSocket(int port, int backlog)sets the maximum queue length of waiting connections.ServerSocket(int port, int backlog, InetAddress bindAddr)binds to one local address of a multi-homed host.
Procedure:
- Create the server socket, e.g.
ServerSocket ss = new ServerSocket(5000);. AnIOExceptionorBindExceptionoccurs if the port is in use or not permitted. - Optionally set options, then (if created unbound) call
ss.bind(new InetSocketAddress(5000), 50). - Call
accept(), which blocks until a client connects and returns aSocket. - Use
getInputStream()andgetOutputStream()of that socket to talk to the client. - Close the client socket, and finally the server socket with
close().
ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(5000), 50);
Socket client = ss.accept();
Server socket options
- SO_TIMEOUT (
setSoTimeout(int ms)):accept()waits at most this long, then throwsSocketTimeoutException. 0 means wait forever.ss.setSoTimeout(10000); - SO_REUSEADDR (
setReuseAddress(true)): allows binding to a port still in TIME_WAIT from a previous run, so a restarted server does not fail. It must be set beforebind(). - SO_RCVBUF (
setReceiveBufferSize(int size)): sets the suggested receive buffer size for accepted sockets (before binding for large windows).ss.setReceiveBufferSize(65536); - Performance preferences (
setPerformancePreferences(connectionTime, latency, bandwidth)): relative importance of the three factors.
The getters getSoTimeout(), getReuseAddress(), getReceiveBufferSize(), getLocalPort() and isBound() return the current values.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
Write a program to perform a basic two-way communication between client and server.
Answer
The server reads a message from the client and replies; the client sends lines typed by the user and prints the replies. Typing bye ends the chat.
TwoWayServer.java
import java.io.*;
import java.net.*;
public class TwoWayServer {
public static void main(String[] args) throws IOException {
try (ServerSocket ss = new ServerSocket(5000)) {
System.out.println("Server waiting...");
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String msg;
while ((msg = in.readLine()) != null) {
System.out.println("Client: " + msg);
if (msg.equalsIgnoreCase("bye")) break;
System.out.print("Server: ");
out.println(kb.readLine());
}
s.close();
}
}
}
TwoWayClient.java
import java.io.*;
import java.net.*;
public class TwoWayClient {
public static void main(String[] args) throws IOException {
try (Socket s = new Socket("localhost", 5000)) {
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String msg;
while (true) {
System.out.print("Client: ");
msg = kb.readLine();
out.println(msg);
if (msg.equalsIgnoreCase("bye")) break;
String reply = in.readLine();
if (reply == null) break;
System.out.println("Server: " + reply);
}
}
}
}
Start the server first, then the client. Each side uses the socket's input and output streams, giving communication in both directions.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
What are the features of DatagramPacket and DatagramSocket Class? Write a program to create a simple UDP client.
Answer
DatagramPacket
A DatagramPacket is a container for one UDP datagram.
- Sending constructor:
DatagramPacket(byte[] data, int length, InetAddress addr, int port)holds the data and the destination. - Receiving constructor:
DatagramPacket(byte[] buf, int length)provides an empty buffer to be filled. - Methods:
getData(),getLength(),getAddress(),getPort(),setData(),setLength(),setAddress(),setPort(). - A UDP packet is limited to 65,507 bytes of data; the packet carries its own addressing, so no connection is needed.
DatagramSocket
A DatagramSocket is the endpoint that sends and receives datagram packets.
- Constructors:
DatagramSocket()(any free local port, typical for clients) andDatagramSocket(int port)(fixed port, for servers). send(DatagramPacket)sends,receive(DatagramPacket)blocks until a packet arrives.setSoTimeout(int ms)limits the blocking time ofreceive().connect()/disconnect()restrict the socket to one remote peer;close()releases the port.- It is connectionless and unreliable: packets may be lost, duplicated or reordered.
Simple UDP client
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress server = InetAddress.getByName("localhost");
byte[] sendData = "Hello UDP Server".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, server, 9876);
socket.send(sendPacket);
byte[] buf = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
socket.setSoTimeout(5000);
socket.receive(receivePacket);
System.out.println("Reply: " + new String(receivePacket.getData(), 0, receivePacket.getLength()));
socket.close();
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What is the use of InetAddress class? Write a program to retrieve IP and MAC addresses?
Answer
InetAddress class
java.net.InetAddress represents an IP address (IPv4 or IPv6) and optionally its host name. It is used to resolve host names to IP addresses through DNS and the reverse, and to get the local host address. Its subclasses are Inet4Address and Inet6Address. It has no public constructors; objects come from static factory methods:
getByName(String host),getAllByName(String host),getByAddress(byte[])getLocalHost(),getLoopbackAddress()- instance methods
getHostName(),getHostAddress(),getAddress(),isReachable(int ms),isLoopbackAddress(),isMulticastAddress().
InetAddress does not give the MAC address, so NetworkInterface.getHardwareAddress() is used for that.
Program to retrieve IP and MAC address
import java.net.*;
public class IpMac {
public static void main(String[] args) throws Exception {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("Host name : " + ip.getHostName());
System.out.println("IP address: " + ip.getHostAddress());
NetworkInterface ni = NetworkInterface.getByInetAddress(ip);
if (ni == null) {
System.out.println("No network interface found for this address");
return;
}
byte[] mac = ni.getHardwareAddress();
if (mac == null) {
System.out.println("MAC address not available");
return;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println("MAC address: " + sb);
}
}
Sample output: IP address: 192.168.1.5 and MAC address: 00-1A-2B-3C-4D-5E.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Define URL class. Write a program to show the parts of the URL (Splitting URL).
Answer
URL class
java.net.URL represents a Uniform Resource Locator, the address of a resource on the Internet, of the form protocol://host:port/path?query#ref. It can be constructed from a string (new URL("http://..."), throws MalformedURLException) or from its parts. Its methods allow reading its components and opening a connection: getProtocol(), getHost(), getPort(), getDefaultPort(), getPath(), getFile(), getQuery(), getRef(), getAuthority(), getUserInfo(), openStream() and openConnection().
Program to split a URL
import java.net.*;
public class SplitURL {
public static void main(String[] args) {
try {
URL u = new URL("https://www.example.com:8080/docs/index.html?id=10&lang=en#intro");
System.out.println("Protocol : " + u.getProtocol());
System.out.println("Host : " + u.getHost());
System.out.println("Port : " + u.getPort());
System.out.println("Default : " + u.getDefaultPort());
System.out.println("Authority : " + u.getAuthority());
System.out.println("Path : " + u.getPath());
System.out.println("File : " + u.getFile());
System.out.println("Query : " + u.getQuery());
System.out.println("Reference : " + u.getRef());
} catch (MalformedURLException e) {
System.out.println("Invalid URL: " + e.getMessage());
}
}
}
Output:
Protocol : https
Host : www.example.com
Port : 8080
Default : 443
Authority : www.example.com:8080
Path : /docs/index.html
File : /docs/index.html?id=10&lang=en
Query : id=10&lang=en
Reference : intro
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Define Socket. Differentiate between TCP and UDP Sockets with their applications.
Answer
Socket
A socket is one endpoint of a two-way communication link between two programs on a network. It is identified by an IP address and a port number. Java provides Socket and ServerSocket for TCP and DatagramSocket for UDP.
TCP versus UDP sockets
| Basis | TCP socket | UDP socket |
|---|---|---|
| Connection | Connection-oriented (three-way handshake) | Connectionless |
| Reliability | Reliable: acknowledgements, retransmission, ordered delivery | Unreliable: loss, duplication, reordering possible |
| Data unit | Byte stream, no message boundaries | Discrete datagrams with boundaries |
| Speed and overhead | Slower, more header and state | Faster, small 8-byte header |
| Flow and congestion control | Yes | No |
| Java classes | Socket, ServerSocket | DatagramSocket, DatagramPacket |
| Broadcast/multicast | Not supported | Supported |
Applications
- TCP: web (HTTP/HTTPS), e-mail (SMTP, POP3), file transfer (FTP), remote login (SSH, Telnet), where correctness matters.
- UDP: DNS queries, video and voice streaming, VoIP, online games, DHCP, SNMP, where speed matters more than occasional loss.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Define cookies. Write a program to retrieve cookie information stored in the system.
Answer
Cookies
A cookie is a small piece of data (name-value pair with attributes such as domain, path, expiry, secure and HttpOnly) that a web server sends to a browser in a Set-Cookie header. The browser stores it and returns it in a Cookie header with later requests to the same site. Cookies maintain state in the stateless HTTP protocol, for example for sessions, login, shopping carts and preferences. In Java they are represented by java.net.HttpCookie, and stored by a CookieManager/CookieStore.
Program to retrieve cookie information
import java.net.*;
import java.util.List;
public class CookieDemo {
public static void main(String[] args) throws Exception {
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URL url = new URL("https://www.google.com");
URLConnection conn = url.openConnection();
conn.getContent(); // makes the request, cookies are stored
CookieStore store = manager.getCookieStore();
List<HttpCookie> cookies = store.getCookies();
for (HttpCookie c : cookies) {
System.out.println("Name : " + c.getName());
System.out.println("Value : " + c.getValue());
System.out.println("Domain : " + c.getDomain());
System.out.println("Path : " + c.getPath());
System.out.println("Max age : " + c.getMaxAge());
System.out.println("Secure : " + c.getSecure());
System.out.println("-----");
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Define IP Multicast. Write a program to join a computer system in a multicast group.
Answer
IP Multicast
IP multicast delivers a datagram from one sender to many receivers that belong to a multicast group, using a single transmission. The group is identified by a class D address (224.0.0.0 to 239.255.255.255), and routers copy the packet only where receivers exist. It is based on UDP, so it is unreliable, and the TTL value controls how far packets travel. It is used for video conferencing, streaming, and service announcements.
Program to join a multicast group
import java.net.*;
public class MulticastReceiver {
public static void main(String[] args) throws Exception {
InetAddress group = InetAddress.getByName("230.0.0.1");
int port = 4446;
MulticastSocket socket = new MulticastSocket(port);
socket.joinGroup(group);
System.out.println("Joined group " + group.getHostAddress());
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
for (int i = 0; i < 5; i++) {
socket.receive(packet);
String msg = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received from " + packet.getAddress() + ": " + msg);
}
socket.leaveGroup(group);
socket.close();
}
}
joinGroup() makes the host a member, so datagrams sent to 230.0.0.1:4446 are received; leaveGroup() removes it. (On newer Java versions joinGroup(SocketAddress, NetworkInterface) is preferred, since the single-argument form is deprecated.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Write Short Notes on (Any Two):
a) HTTP
b) RMI
c) Secure Socket
Answer
(a) HTTP
HTTP (HyperText Transfer Protocol) is the application-layer protocol of the World Wide Web, running over TCP (default port 80; HTTPS uses 443). It follows a stateless request-response model: the client sends a request line (method, URL, version), headers and an optional body; the server returns a status line (e.g. 200 OK, 404 Not Found), headers and a body. Common methods are GET, POST, PUT, DELETE and HEAD. Status codes are grouped as 1xx informational, 2xx success, 3xx redirection, 4xx client error and 5xx server error. Statelessness is overcome with cookies and sessions. HTTP/1.1 added persistent connections, and HTTP/2 added multiplexing.
(b) RMI
Remote Method Invocation lets an object in one JVM call methods on an object in another JVM as if it were local. A remote interface extends java.rmi.Remote, and each method declares RemoteException. The server class implements it (extending UnicastRemoteObject), and is registered in the RMI registry with Naming.rebind(). The client gets a stub (proxy) using Naming.lookup(); the stub marshals arguments by serialization and sends them to the server's skeleton/dispatcher. Parameters and return values must be serializable. RMI hides the network details and supports distributed Java applications.
(c) Secure Socket
A secure socket is a socket that uses SSL/TLS to provide encryption, server (and optional client) authentication and message integrity. Java's JSSE package javax.net.ssl provides SSLSocket and SSLServerSocket, created by SSLSocketFactory and SSLServerSocketFactory. A handshake negotiates the cipher suite, authenticates using X.509 certificates, and exchanges session keys; afterwards data is encrypted. Keys and certificates are held in keystores. HTTPS is HTTP over such a socket.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
Write multithreaded TCP client and server socket programs for daytime service.
Answer
The server creates a new thread for every client connection, so many clients can get the time concurrently.
MTDaytimeServer.java
import java.io.*;
import java.net.*;
import java.util.Date;
public class MTDaytimeServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(1313);
System.out.println("Multithreaded daytime server started on port 1313");
while (true) {
Socket client = server.accept();
new ClientHandler(client).start();
}
}
}
class ClientHandler extends Thread {
private final Socket client;
ClientHandler(Socket client) { this.client = client; }
@Override
public void run() {
try (PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
out.println(new Date().toString());
} catch (IOException e) {
System.err.println("Error: " + e);
} finally {
try { client.close(); } catch (IOException ignored) {}
}
}
}
DaytimeClient.java
import java.io.*;
import java.net.*;
public class DaytimeClient {
public static void main(String[] args) throws IOException {
try (Socket s = new Socket("localhost", 1313);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
System.out.println("Server time: " + in.readLine());
}
}
}
Port 1313 is used because the standard port 13 needs administrator privileges. The accept() loop in the main thread only accepts connections; each ClientHandler thread serves its client independently.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
Write UDP client and server socket programs in which the server identifies the number sent by a client is either even or odd and replies to the client accordingly.
Answer
The client sends a number as text in a datagram; the server parses it, decides even or odd, and replies.
UDPEvenOddServer.java
import java.net.*;
public class UDPEvenOddServer {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9876);
System.out.println("UDP server running on port 9876");
byte[] buf = new byte[1024];
while (true) {
DatagramPacket request = new DatagramPacket(buf, buf.length);
socket.receive(request);
String text = new String(request.getData(), 0, request.getLength()).trim();
String reply;
try {
int n = Integer.parseInt(text);
reply = n + " is " + (n % 2 == 0 ? "even" : "odd");
} catch (NumberFormatException e) {
reply = "Invalid number";
}
byte[] data = reply.getBytes();
DatagramPacket response = new DatagramPacket(data, data.length,
request.getAddress(), request.getPort());
socket.send(response);
}
}
}
UDPEvenOddClient.java
import java.net.*;
import java.util.Scanner;
public class UDPEvenOddClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress server = InetAddress.getByName("localhost");
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = sc.nextLine();
byte[] data = num.getBytes();
socket.send(new DatagramPacket(data, data.length, server, 9876));
byte[] buf = new byte[1024];
DatagramPacket reply = new DatagramPacket(buf, buf.length);
socket.setSoTimeout(5000);
socket.receive(reply);
System.out.println("Server: " + new String(reply.getData(), 0, reply.getLength()));
socket.close();
}
}
Example: entering 7 prints Server: 7 is odd; entering 10 prints Server: 10 is even.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
How blocking I/O is different from Non-Blocking I/O? Explain the basic mechanism of handling Buffers and Channels in Java with an example.
Answer
Blocking versus non-blocking I/O
| Basis | Blocking I/O (java.io, java.net) | Non-blocking I/O (java.nio) |
|---|---|---|
| Waiting | The thread waits in read(), write() or accept() until the operation finishes | Calls return at once; the thread can do other work |
| Model | Stream oriented, one byte at a time, one direction | Buffer and channel oriented, can read and write on the same channel |
| Threads | Typically one thread per connection | One thread with a Selector can serve thousands of connections |
| Readiness | Not known in advance | Selector reports ready channels (accept, connect, read, write) |
| Complexity | Simple | More complex |
| Scalability | Limited by thread count and memory | High |
Buffers and channels
A channel (FileChannel, SocketChannel, ServerSocketChannel, DatagramChannel) is a connection to a file, socket or device through which data is transferred. Data is never read or written to a channel directly: it always goes through a buffer (ByteBuffer, CharBuffer, IntBuffer and so on), a block of memory with three key properties:
- capacity: the fixed maximum number of elements.
- position: the index of the next element to read or write.
- limit: the first index that must not be read or written.
Mechanism:
- Allocate a buffer:
ByteBuffer.allocate(1024)(orallocateDirect). - Channel reads data into the buffer:
channel.read(buffer)(buffer in write mode). - Call
buffer.flip()to switch to read mode (limit = position, position = 0). - Process or write out the data:
channel.write(buffer)orbuffer.get(). - Call
buffer.clear()(orcompact()) to prepare it for reuse.
For sockets, a channel is set non-blocking with configureBlocking(false) and registered with a Selector using register(selector, SelectionKey.OP_READ).
Example: copying a file with channels and a buffer
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelCopy {
public static void main(String[] args) throws IOException {
try (FileChannel in = new FileInputStream("source.txt").getChannel();
FileChannel out = new FileOutputStream("target.txt").getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (in.read(buffer) != -1) {
buffer.flip(); // switch to reading
while (buffer.hasRemaining()) {
out.write(buffer);
}
buffer.clear(); // ready for next read
}
}
System.out.println("File copied");
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Define the client-server model of a network application. Explain the design considerations for a network application.
Answer
Client-server model
In the client-server model of a network application, the work is divided between a server, which provides a service or resource and listens for requests at a known address and port, and clients, which start communication, send requests and use the responses. The server is usually always running and may serve many clients at the same time. The model may be iterative (one client at a time) or concurrent (threads or processes per client). Examples are web, e-mail, FTP and database applications.
Design considerations for a network application
- Protocol design: define message formats, commands, states and error handling; text or binary; stateless or stateful.
- Choice of transport: TCP for reliability and ordering, UDP for speed and multicast.
- Concurrency: use multithreading, thread pools or non-blocking I/O so one slow client does not block others.
- Scalability and performance: number of clients, bandwidth, latency, caching, buffering and load balancing.
- Reliability and fault tolerance: handle timeouts, lost connections, retries, server crashes and partial data.
- Security: authentication, authorisation, encryption (SSL/TLS), input validation, protection against attacks.
- Resource management: closing sockets and streams, limiting connections, memory use.
- Portability and interoperability: data representation (byte order, character encoding, serialization) so different platforms can communicate.
- Naming and addressing: use of DNS names, ports and service discovery.
- Maintainability and usability: logging, monitoring, configuration and clear error messages.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Write a program to show the IP and MAC address of the system and also check if the IP address is IPv4 or IPv6.
Answer
InetAddress can be an Inet4Address or Inet6Address, which tells the IP version. The MAC address comes from NetworkInterface.getHardwareAddress().
import java.net.*;
import java.util.*;
public class IpMacVersion {
public static void main(String[] args) throws Exception {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
if (!ni.isUp() || ni.isLoopback()) continue;
byte[] mac = ni.getHardwareAddress();
String macStr = "N/A";
if (mac != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], i < mac.length - 1 ? "-" : ""));
}
macStr = sb.toString();
}
System.out.println("Interface: " + ni.getDisplayName());
System.out.println("MAC : " + macStr);
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress a = addrs.nextElement();
String type = (a instanceof Inet4Address) ? "IPv4"
: (a instanceof Inet6Address) ? "IPv6" : "Unknown";
System.out.println("IP : " + a.getHostAddress() + " (" + type + ")");
}
System.out.println();
}
}
}
Sample output:
Interface: eth0
MAC : 00-1A-2B-3C-4D-5E
IP : fe80:0:0:0:21a:2bff:fe3c:4d5e%eth0 (IPv6)
IP : 192.168.1.5 (IPv4)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Define URL Connection Class? Write a program to read header using header-specific methods.
Answer
URLConnection class
java.net.URLConnection is an abstract class that represents a communication link between the application and a resource named by a URL. It is obtained with url.openConnection(), and is more flexible than url.openStream(): it lets the program read response headers, set request properties (setRequestProperty()), write to the server (setDoOutput(true)), and control timeouts and caching. Its subclass HttpURLConnection adds HTTP specific features such as the request method and status code. The usual steps are: create the connection, set parameters, connect, read headers and content.
Header-specific methods: getContentType(), getContentLength(), getContentEncoding(), getDate(), getExpiration(), getLastModified(); generic access is by getHeaderField(String name), getHeaderField(int n) and getHeaderFieldKey(int n).
import java.net.*;
import java.util.Date;
public class ReadHeaders {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
URLConnection conn = url.openConnection();
System.out.println("Content-Type : " + conn.getContentType());
System.out.println("Content-Length : " + conn.getContentLength());
System.out.println("Content-Encoding: " + conn.getContentEncoding());
System.out.println("Date : " + new Date(conn.getDate()));
System.out.println("Last-Modified : " + new Date(conn.getLastModified()));
System.out.println("Expiration : " + conn.getExpiration());
System.out.println("\nAll headers:");
for (int i = 1; ; i++) {
String key = conn.getHeaderFieldKey(i);
String value = conn.getHeaderField(i);
if (key == null && value == null) break;
System.out.println(key + ": " + value);
}
}
}
getLastModified() and getExpiration() return 0 if the header is absent, which is shown as 1 January 1970.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Write the functions of Socket. Explain the configuration options of a TCP client socket.
Answer
A socket is one endpoint of a two-way communication link between two programs on a network. In Java, java.net.Socket represents the client side of a TCP connection.
Functions of a socket
- Connect to a remote host and port (
connect). - Send data to the remote host through an output stream.
- Receive data from the remote host through an input stream.
- Close the connection (
close). - (Server side,
ServerSocket) bind to a port, listen, and accept incoming connections.
Configuration options of a TCP client socket
Constructors let the socket connect immediately, e.g. new Socket("host", 80), or stay unconnected, new Socket(), so that options can be set before connect(SocketAddress, timeout). The main options are:
- SO_TIMEOUT (
setSoTimeout(ms)): a blocking read throwsSocketTimeoutExceptionafter the given time. 0 means wait forever. - TCP_NODELAY (
setTcpNoDelay(true)): disables Nagle's algorithm so small packets are sent at once, useful for interactive traffic. - SO_LINGER (
setSoLinger(on, seconds)): decides whatclose()does with unsent data, either wait up to the given seconds or discard it. - SO_KEEPALIVE (
setKeepAlive(true)): sends occasional probes on an idle connection to detect a dead peer. - SO_RCVBUF / SO_SNDBUF (
setReceiveBufferSize,setSendBufferSize): size of the receive and send buffers. - SO_REUSEADDR (
setReuseAddress(true)): allows binding to an address still in TIME_WAIT. - OOBINLINE (
setOOBInline): treats TCP urgent data as ordinary data in the input stream. - Traffic class (
setTrafficClass): sets the IP type-of-service / DSCP bits.
Socket s = new Socket();
s.setSoTimeout(5000);
s.setTcpNoDelay(true);
s.connect(new InetSocketAddress("example.com", 80), 3000);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Define a secure socket. Write a program to create a secure client socket.
Answer
A secure socket is a socket whose communication is protected by SSL/TLS, giving confidentiality (encryption), integrity (tamper detection) and authentication (the server, and optionally the client, proves its identity by certificate). In Java it is provided by JSSE through javax.net.ssl.SSLSocket, created by an SSLSocketFactory.
Program: secure client socket
import javax.net.ssl.*;
import java.io.*;
public class SecureClient {
public static void main(String[] args) throws Exception {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try (SSLSocket socket = (SSLSocket) factory.createSocket("www.example.com", 443)) {
socket.startHandshake(); // negotiate cipher suite, verify certificate
Writer out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
out.write("GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
}
}
Steps: obtain the default SSLSocketFactory, create an SSLSocket to the server's HTTPS port (443), run the handshake, then use the normal input and output streams. Data is encrypted and decrypted transparently.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Define Buffer. Explain buffer handling methods.
Answer
A buffer is a fixed-size block of memory, a container for primitive data of one type, used to hold data while it moves between a program and a channel (file or network). In Java NIO, java.nio.Buffer is the abstract base of ByteBuffer, CharBuffer, IntBuffer, LongBuffer, FloatBuffer, DoubleBuffer and ShortBuffer.
Key properties: capacity (maximum elements, fixed), limit (first index that must not be read or written), position (index of the next element), and an optional mark. They always satisfy .
Buffer handling methods
- Creating:
allocate(n)(heap buffer),allocateDirect(n)(native memory),wrap(array)(backed by an existing array). - Writing / reading: relative
put(x)andget()move the position; absoluteput(i, x)andget(i)do not. Bulk formsput(array)andget(array)exist. flip(): sets limit = position, position = 0. Used to switch from writing to reading.clear(): position = 0, limit = capacity. Prepares for writing again (data is not erased).rewind(): position = 0, limit unchanged, so the data can be re-read.compact(): copies the unread data to the start and prepares to write after it.mark()andreset(): remember a position and return to it.remaining()andhasRemaining(): number of elements between position and limit.slice(),duplicate(),asReadOnlyBuffer(): views sharing the same content.
Typical use: put data, flip(), then channel.write(buf); or channel.read(buf), flip(), then get.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Write short notes on (any two):
a) HTTP methods
b) Datagram Packet
c) Multicast Socket
Answer
(a) HTTP methods
HTTP methods (verbs) tell the server what action to perform on a resource identified by a URL.
- GET: retrieves a resource; parameters appear in the URL; safe and idempotent.
- POST: sends data in the request body (form submission, creating a resource); not idempotent.
- PUT: replaces or creates the resource at the URL; idempotent.
- DELETE: removes the resource.
- HEAD: like GET but returns only the headers.
- OPTIONS: asks which methods the server supports.
- TRACE and PATCH (partial update) also exist.
In Java, HttpURLConnection.setRequestMethod("POST") selects the method; for POST the connection must have setDoOutput(true) before writing the body.
(b) Datagram Packet
A java.net.DatagramPacket is the unit of data sent or received over UDP. It holds a byte array, the number of bytes, and the remote address and port.
- Sending constructor:
new DatagramPacket(byte[] data, int length, InetAddress addr, int port). - Receiving constructor:
new DatagramPacket(byte[] buf, int length). - Methods:
getData(),getLength(),getAddress(),getPort(),setData(),setLength().
A packet is sent with DatagramSocket.send(packet) and received with receive(packet). UDP gives no delivery or ordering guarantee, and the maximum payload is about 65,507 bytes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
a) Differentiate between URL and URI class with their applications.
b) Write any program to illustrate the application of RMI.
Answer
(a) URL and URI
A URI (Uniform Resource Identifier) is a string that identifies a resource, by name, by location, or both. A URL (Uniform Resource Locator) is a URI that also says how to locate the resource, with a protocol such as http, ftp or file. Every URL is a URI, but not every URI is a URL (for example urn:isbn:0451450523 is a URN).
| Aspect | java.net.URI | java.net.URL |
|---|---|---|
| Purpose | Parses and manipulates identifiers syntactically | Locates a resource and can retrieve it |
| Network access | None | openStream(), openConnection() |
| Protocol handler | Not needed, so any scheme (urn, tel) works | Needs a handler for the scheme, otherwise MalformedURLException |
| Operations | resolve(), relativize(), normalize() | Fetch data, get content |
| Equality | Purely string-based comparison | equals() may involve DNS lookup |
| Conversion | uri.toURL() | url.toURI() |
Applications: URI for validating, resolving and building identifiers (for example relative links, XML namespaces); URL for downloading web pages, reading files and connecting to servers.
(b) RMI program
RMI lets an object in one JVM invoke methods of an object in another JVM. Example: a remote greeting and addition service.
Remote interface
import java.rmi.*;
public interface Calc extends Remote {
int add(int a, int b) throws RemoteException;
String greet(String name) throws RemoteException;
}
Implementation
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class CalcImpl extends UnicastRemoteObject implements Calc {
public CalcImpl() throws RemoteException { super(); }
public int add(int a, int b) { return a + b; }
public String greet(String name) { return "Hello, " + name; }
}
Server
import java.rmi.registry.*;
public class Server {
public static void main(String[] args) throws Exception {
Registry reg = LocateRegistry.createRegistry(1099);
reg.rebind("CalcService", new CalcImpl());
System.out.println("Server ready");
}
}
Client
import java.rmi.registry.*;
public class Client {
public static void main(String[] args) throws Exception {
Registry reg = LocateRegistry.getRegistry("localhost", 1099);
Calc c = (Calc) reg.lookup("CalcService");
System.out.println(c.add(5, 7)); // 12
System.out.println(c.greet("Nepal"));
}
}
Run the server first, then the client. The stub is generated dynamically, so no rmic is needed in modern Java.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
Write a TCP multithreaded server and client socket program to check the number sent by the client is either prime or composite.
Answer
The server accepts each client in a new thread, so many clients can be served at once. The client sends an integer and the server replies whether it is prime or composite.
Server
import java.io.*;
import java.net.*;
public class PrimeServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5000);
System.out.println("Server waiting on port 5000...");
while (true) {
Socket client = server.accept();
new Thread(new Handler(client)).start(); // one thread per client
}
}
}
class Handler implements Runnable {
private final Socket socket;
Handler(Socket s) { socket = s; }
public void run() {
try (DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
int n = in.readInt();
out.writeUTF(n + " is " + (isPrime(n) ? "Prime" : "Composite"));
} catch (IOException e) {
e.printStackTrace();
} finally {
try { socket.close(); } catch (IOException ignored) {}
}
}
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; (long) i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
}
Client
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class PrimeClient {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
try (Socket s = new Socket("localhost", 5000);
DataOutputStream out = new DataOutputStream(s.getOutputStream());
DataInputStream in = new DataInputStream(s.getInputStream())) {
out.writeInt(n);
System.out.println("Server: " + in.readUTF());
}
}
}
Sample run: input 17 gives "17 is Prime"; input 18 gives "18 is Composite". Numbers below 2 are neither, and the code reports them as Composite (not prime). The loop to is enough because any composite number has a factor not exceeding .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
Write a program to create a UDP server and client which converts the date from the client in BS to AD format. [Assume that the difference between BS and AD is 56 years, 08 months, 17 days]
Answer
UDP is connectionless, so the client sends the BS date as a datagram and the server replies with the AD date. The conversion is the stated rule: AD = BS minus 56 years, 8 months, 17 days, applied with java.time.LocalDate.
Example check: BS 2080-05-20 gives 2080 - 56 = 2024, month 5 - 8 gives month 9 of 2023, so 2023-09-20 minus 17 days is 2023-09-03.
Server
import java.net.*;
import java.time.LocalDate;
public class DateServer {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9876);
byte[] buf = new byte[1024];
System.out.println("UDP server started on 9876");
while (true) {
DatagramPacket req = new DatagramPacket(buf, buf.length);
socket.receive(req);
String bs = new String(req.getData(), 0, req.getLength()).trim(); // yyyy-MM-dd
String reply;
try {
LocalDate ad = LocalDate.parse(bs)
.minusYears(56).minusMonths(8).minusDays(17);
reply = "AD date: " + ad;
} catch (Exception e) {
reply = "Invalid date. Use yyyy-MM-dd";
}
byte[] out = reply.getBytes();
socket.send(new DatagramPacket(out, out.length, req.getAddress(), req.getPort()));
}
}
}
Client
import java.net.*;
import java.util.Scanner;
public class DateClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
System.out.print("Enter BS date (yyyy-MM-dd): ");
byte[] data = sc.nextLine().getBytes();
InetAddress host = InetAddress.getByName("localhost");
socket.send(new DatagramPacket(data, data.length, host, 9876));
byte[] buf = new byte[1024];
DatagramPacket resp = new DatagramPacket(buf, buf.length);
socket.receive(resp);
System.out.println(new String(resp.getData(), 0, resp.getLength()));
socket.close();
}
}
Years are subtracted first, then months, then days, which is the order LocalDate applies. The server runs in a loop so it can serve many clients.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Describe the process of reading the Header using URL Connection.
Answer
An HTTP response consists of a status line, header fields (name: value pairs), a blank line and the body. java.net.URLConnection provides methods to read the headers after the connection is made.
Process
- Create a
URLobject and callopenConnection()to get aURLConnection(anHttpURLConnectionfor http). - Optionally set request properties (
setRequestProperty). - Reading any header (or the stream) triggers
connect()and sends the request. - Read the headers using:
- Specific getters:
getContentType(),getContentLength(),getContentEncoding(),getDate(),getExpiration(),getLastModified(). getHeaderField(String name)orgetHeaderField(int n).getHeaderFieldKey(int n)for the name of the n-th header.getHeaderFields(), which returns aMap<String, List<String>>of all headers.
- Specific getters:
import java.net.*;
import java.util.*;
public class ReadHeaders {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
URLConnection conn = url.openConnection();
System.out.println("Type: " + conn.getContentType());
System.out.println("Length: " + conn.getContentLength());
System.out.println("Modified: " + new Date(conn.getLastModified()));
for (int i = 1; ; i++) { // loop through all headers
String key = conn.getHeaderFieldKey(i);
String val = conn.getHeaderField(i);
if (val == null) break;
System.out.println(key + ": " + val);
}
}
}
Header 0 is the status line and has no key, which is why the loop starts at 1.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Explain about X-www-form URI Encoder and URI Decoder with an example.
Answer
URLs may contain only a limited set of ASCII characters. Spaces and special characters must be converted to the application/x-www-form-urlencoded format, which is what HTML forms use when sending data.
URLEncoder (java.net.URLEncoder.encode(String s, String charset)) applies these rules:
- Letters, digits,
.,-,*and_are left unchanged. - A space becomes
+. - Every other character is converted to bytes in the given charset and written as
%XY, where XY is the hexadecimal value of each byte.
URLDecoder (java.net.URLDecoder.decode(String s, String charset)) reverses the process: + becomes a space and %XY is converted back to the original character.
import java.net.*;
public class EncodeDemo {
public static void main(String[] args) throws Exception {
String original = "name=Ram Sharma&city=Kathmandu/Nepal";
String encoded = URLEncoder.encode(original, "UTF-8");
System.out.println(encoded);
String decoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println(decoded);
}
}
Output:
name%3DRam+Sharma%26city%3DKathmandu%2FNepal
name=Ram Sharma&city=Kathmandu/Nepal
Encode each name and value separately, not the whole URL, otherwise the separators =, & and / are also encoded.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is the significance to control HTTP Keep-Alive system properties. Write a Program for a cookie policy that blocks all .gov cookies but allows others.
Answer
Significance of HTTP Keep-Alive properties
HTTP/1.1 keeps the TCP connection open after a response so that several requests reuse it. This saves the cost of repeated TCP handshakes (and TLS handshakes), reduces latency, and lowers load on the server. Java's HttpURLConnection supports this by default and the behaviour is controlled by system properties:
http.keepAlive(defaulttrue): turns persistent connections on or off.http.maxConnections(default 5): the maximum number of idle connections kept per destination.http.keepAlive.time.server/http.keepAlive.time.proxy: how long an idle connection may be kept.
Setting http.keepAlive=false forces a new connection per request, useful for debugging or when a server misbehaves. Raising http.maxConnections suits clients that fetch many resources from one host. To reuse a connection, the response body must be fully read and the stream closed.
Program: cookie policy that blocks .gov cookies
import java.io.IOException;
import java.net.*;
public class NoGovCookies implements CookiePolicy {
@Override
public boolean shouldAccept(URI uri, HttpCookie cookie) {
String host = uri.getHost();
return host == null || !host.toLowerCase().endsWith(".gov");
}
public static void main(String[] args) throws IOException {
CookieManager manager = new CookieManager(null, new NoGovCookies());
CookieHandler.setDefault(manager);
URL url = new URL("https://www.example.com");
url.openConnection().getContent(); // cookies from .gov hosts are ignored
System.out.println(manager.getCookieStore().getCookies());
}
}
CookiePolicy.shouldAccept is called for each cookie; returning false for hosts ending in .gov rejects them, and all others are stored.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is Java Secure Sockets Extension? Write a program for creating secure sockets with tufoshss.edu.np.
Answer
Java Secure Sockets Extension (JSSE) is the Java API (packages javax.net, javax.net.ssl, javax.security.cert) that implements SSL and TLS. It provides encryption, server (and optional client) authentication and message integrity for socket communication. Its main classes are SSLSocketFactory, SSLSocket, SSLServerSocketFactory, SSLServerSocket, SSLContext, TrustManager and KeyManager. It is built into the JDK, so no separate library is needed.
Program: secure socket to tufoshss.edu.np
import javax.net.ssl.*;
import java.io.*;
public class SecureTU {
public static void main(String[] args) {
String host = "tufoshss.edu.np";
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try (SSLSocket socket = (SSLSocket) factory.createSocket(host, 443)) {
socket.startHandshake();
System.out.println("Protocol: " + socket.getSession().getProtocol());
System.out.println("Cipher: " + socket.getSession().getCipherSuite());
Writer out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
out.write("GET / HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) System.out.println(line);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
The default factory trusts the certificates in the JDK's trust store, so the handshake verifies the server's certificate before any data is exchanged.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Explain central abstractions of Java NIO.
Answer
Java NIO (New I/O, java.nio) is a buffer-oriented, channel-based and non-blocking alternative to stream I/O, designed for scalable network servers. Its central abstractions are:
-
Buffers: containers (
ByteBuffer,CharBuffer, etc.) holding data to be read or written. They have capacity, limit and position, and are used throughput,get,flipandclear. Direct buffers can use native memory for speed. -
Channels: connections to entities that perform I/O (files, sockets). Unlike streams they are bidirectional and can be non-blocking. Main types are
FileChannel,SocketChannel,ServerSocketChannelandDatagramChannel. Data always moves between a channel and a buffer:channel.read(buffer)andchannel.write(buffer). -
Selectors: let one thread monitor many channels. A channel is registered with a selector for events (
OP_ACCEPT,OP_CONNECT,OP_READ,OP_WRITE);select()returns the channels that are ready. -
SelectionKey: represents the registration of a channel with a selector; it holds the interest set, the ready set and an optional attachment.
-
Charsets (encoders and decoders): convert between bytes and characters (
Charset,CharsetEncoder,CharsetDecoder).
Together they allow a single thread to handle thousands of connections without a thread per client.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Describe about UDP Socket Option and Write a Program for Scanning Local UDP Ports from 1024 port to up.
Answer
UDP socket options (set on DatagramSocket)
- SO_TIMEOUT (
setSoTimeout):receive()throwsSocketTimeoutExceptionif no packet arrives in the given time. - SO_RCVBUF / SO_SNDBUF: sizes of the receive and send buffers; a small receive buffer can cause dropped datagrams.
- SO_REUSEADDR: allows several sockets to bind the same address and port (mainly multicast).
- SO_BROADCAST (
setBroadcast): permits sending to a broadcast address. - IP_TOS / traffic class (
setTrafficClass): sets the type of service of the outgoing packets.
Program: scan local UDP ports from 1024 upward
A port is in use if binding a DatagramSocket to it fails with a SocketException.
import java.net.*;
public class UdpPortScanner {
public static void main(String[] args) {
for (int port = 1024; port <= 65535; port++) {
try (DatagramSocket ds = new DatagramSocket(port)) {
// bound successfully, so the port is free
} catch (SocketException e) {
System.out.println("UDP port " + port + " is in use");
}
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Define Multicast Group, and briefly explain the process of working with Multicast Sockets?
Answer
Multicast group
A multicast group is a set of hosts that have joined a common multicast IP address (class D, 224.0.0.0 to 239.255.255.255), so that one datagram sent to that address is delivered to every member. Membership is dynamic: hosts join and leave at any time, and a sender need not be a member. It is more efficient than sending separate unicast copies and is used in video streaming and stock tickers.
Working with multicast sockets (java.net.MulticastSocket)
- Create a
MulticastSocketbound to the group port:new MulticastSocket(4446). - Join the group:
socket.joinGroup(InetAddress.getByName("230.0.0.1"))(newer form takes aSocketAddressand aNetworkInterface). - Send: build a
DatagramPacketaddressed to the group address and port, thensocket.send(packet). Optionally set the range withsetTimeToLive(n). - Receive:
socket.receive(packet)returns datagrams sent to the group. - Leave:
socket.leaveGroup(group), thensocket.close().
MulticastSocket ms = new MulticastSocket(4446);
InetAddress group = InetAddress.getByName("230.0.0.1");
ms.joinGroup(group);
byte[] buf = new byte[256];
DatagramPacket p = new DatagramPacket(buf, buf.length);
ms.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
ms.leaveGroup(group);
ms.close();
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
Explain the factory method with an example. Write a program to download a webpage.
Answer
Factory method
A factory method is a static or instance method that creates and returns objects, hiding the exact class being instantiated, instead of the caller using new directly. It lets the library choose the right implementation at run time. In network programming:
InetAddress.getByName(host),getLocalHost(),getAllByName()createInetAddressobjects (the class has no public constructor).SocketFactory.getDefault().createSocket(host, port)andSSLSocketFactorycreate plain or secure sockets.URL.openConnection()returns anHttpURLConnectionor otherURLConnectiondepending on the protocol.
InetAddress a = InetAddress.getByName("www.google.com"); // factory method
System.out.println(a.getHostAddress());
The caller works with the general type while the factory decides on the concrete class, so the code stays flexible.
Program: download a web page
import java.io.*;
import java.net.*;
public class DownloadPage {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.example.com/");
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
PrintWriter out = new PrintWriter(new FileWriter("page.html"))) {
String line;
while ((line = in.readLine()) != null) {
out.println(line);
}
System.out.println("Page saved to page.html");
}
}
}
url.openStream() connects to the server, sends a GET request and returns the response body; the loop copies it to a file.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
What are the key differences between Socket and Server Socket? Create a simple console chat application using TCP socket.
Answer
Differences between Socket and ServerSocket
| Aspect | Socket | ServerSocket |
|---|---|---|
| Role | Client endpoint of a connection (also the server's per-client endpoint) | Server endpoint that listens for connections |
| Created with | Host and port of the server | Local port to listen on |
| Key method | connect(), getInputStream(), getOutputStream() | accept(), which blocks and returns a Socket |
| Data transfer | Sends and receives data | Does not transfer data itself |
| Number | One per connection | One per listening port |
| Typical options | TCP_NODELAY, SO_LINGER, SO_TIMEOUT | Backlog queue length, SO_REUSEADDR |
Console chat application (TCP)
Server
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6000);
System.out.println("Waiting for client...");
Socket s = ss.accept();
BufferedReader net = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String msg;
while ((msg = net.readLine()) != null) {
System.out.println("Client: " + msg);
if (msg.equalsIgnoreCase("bye")) break;
System.out.print("Server: ");
String reply = kb.readLine();
out.println(reply);
if (reply.equalsIgnoreCase("bye")) break;
}
s.close();
ss.close();
}
}
Client
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 6000);
BufferedReader net = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String msg;
while (true) {
System.out.print("Client: ");
msg = kb.readLine();
out.println(msg);
if (msg.equalsIgnoreCase("bye")) break;
String reply = net.readLine();
if (reply == null) break;
System.out.println("Server: " + reply);
if (reply.equalsIgnoreCase("bye")) break;
}
s.close();
}
}
The two sides take turns; typing bye ends the chat. println with auto-flush ensures each line is sent immediately.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
a) Write a program to calculate the area of a triangle using RMI.
b) Write a program to list out all the interfaces.
Answer
(a) Area of a triangle using RMI
Area . For example, base 10 and height 6 give .
Remote interface
import java.rmi.*;
public interface Triangle extends Remote {
double area(double base, double height) throws RemoteException;
}
Implementation
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class TriangleImpl extends UnicastRemoteObject implements Triangle {
public TriangleImpl() throws RemoteException { super(); }
public double area(double base, double height) { return 0.5 * base * height; }
}
Server
import java.rmi.registry.*;
public class AreaServer {
public static void main(String[] args) throws Exception {
Registry r = LocateRegistry.createRegistry(1099);
r.rebind("TriangleService", new TriangleImpl());
System.out.println("Server ready");
}
}
Client
import java.rmi.registry.*;
public class AreaClient {
public static void main(String[] args) throws Exception {
Registry r = LocateRegistry.getRegistry("localhost", 1099);
Triangle t = (Triangle) r.lookup("TriangleService");
System.out.println("Area = " + t.area(10, 6)); // 30.0
}
}
(b) Program to list all the interfaces
This lists all the network interfaces of the machine using NetworkInterface.
import java.net.*;
import java.util.*;
public class ListInterfaces {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> list = NetworkInterface.getNetworkInterfaces();
while (list.hasMoreElements()) {
NetworkInterface ni = list.nextElement();
System.out.println(ni.getName() + " (" + ni.getDisplayName() + ")");
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
System.out.println(" " + addrs.nextElement().getHostAddress());
}
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is Network Programming? Explain the basic feature of InetAddress Class.
Answer
Network programming
Network programming is writing programs that communicate with other programs running on the same or different computers over a network, using protocols such as TCP, UDP and HTTP. The programs exchange data through sockets, usually in a client-server model. Java supports this through the java.net package (sockets, URLs, datagrams) and java.nio for non-blocking I/O.
Basic features of the InetAddress class
java.net.InetAddress represents an IP address (IPv4 or IPv6) together with an optional host name.
- It has no public constructor; objects are created with factory methods:
getByName(String host),getAllByName(String host),getByAddress(byte[] addr),getLocalHost(),getLoopbackAddress(). getHostName()returns the host name (a reverse DNS lookup if needed) andgetHostAddress()returns the address as text such as192.168.1.5.getAddress()returns the raw address bytes.isReachable(timeout)tests whether the host responds.- Test methods:
isLoopbackAddress(),isSiteLocalAddress(),isMulticastAddress(),isAnyLocalAddress(). - It performs DNS lookups and caches the results; two subclasses exist,
Inet4AddressandInet6Address. - Objects are immutable and can be used as keys.
InetAddress a = InetAddress.getByName("www.google.com");
System.out.println(a.getHostName() + " : " + a.getHostAddress());
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Define Socket and explain its basic operations.
Answer
Socket
A socket is one endpoint of a two-way communication link between two programs over a network. It is identified by an IP address and a port number, and a connection is identified by the pair of sockets (source IP:port, destination IP:port). In Java, Socket is the client endpoint of a TCP connection and ServerSocket the listening endpoint of a server.
Basic operations
- Connect: open a connection to a remote host and port.
- Send data: write bytes to the socket's output stream.
- Receive data: read bytes from the socket's input stream.
- Close: release the connection.
For the server side, two further operations apply:
- Bind: attach to a local port.
- Listen and accept: wait for incoming connections and return a new
Socketfor each client.
Socket s = new Socket("localhost", 5000); // connect
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("Hello"); // send
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine()); // receive
s.close(); // close
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Write the major methods consist in network interface class and also write a program that list all the network interface
Answer
java.net.NetworkInterface represents a network interface, either physical (an Ethernet or Wi-Fi card) or virtual (loopback), with its name and the IP addresses assigned to it.
Major methods
static Enumeration<NetworkInterface> getNetworkInterfaces(): all interfaces of the machine.static NetworkInterface getByName(String name): finds an interface by name, such aseth0.static NetworkInterface getByInetAddress(InetAddress addr): the interface holding the address.String getName()andString getDisplayName(): the interface names.Enumeration<InetAddress> getInetAddresses(): the addresses bound to it.List<InterfaceAddress> getInterfaceAddresses(): addresses with prefix length and broadcast.byte[] getHardwareAddress(): the MAC address.boolean isUp(),isLoopback(),isVirtual(),isPointToPoint(),supportsMulticast().int getMTU(): maximum transmission unit.Enumeration<NetworkInterface> getSubInterfaces()andgetParent().
Program: list all network interfaces
import java.net.*;
import java.util.*;
public class ShowInterfaces {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = en.nextElement();
System.out.println("Name: " + ni.getName() + ", Display: " + ni.getDisplayName()
+ ", Up: " + ni.isUp() + ", Loopback: " + ni.isLoopback());
for (Enumeration<InetAddress> a = ni.getInetAddresses(); a.hasMoreElements();) {
System.out.println(" Address: " + a.nextElement().getHostAddress());
}
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What are SSL sessions, and why are they useful?
Answer
SSL session
An SSL (TLS) session is a logical association between a client and a server created by a full handshake. During the handshake the two sides agree on the protocol version and cipher suite, authenticate using certificates, and establish a shared master secret from which the encryption and MAC keys are derived. The session is identified by a session ID and holds this negotiated state (cipher suite, master secret, peer certificates). In JSSE it is represented by SSLSession, obtained from SSLSocket.getSession(). Many connections can share one session.
Why sessions are useful
- Performance: a full handshake needs public-key operations (RSA or Diffie-Hellman) which are expensive. A new connection that resumes an existing session skips them and reuses the master secret, so it starts faster and uses less CPU.
- Fewer round trips: an abbreviated handshake lowers latency, important when a client such as a browser opens many connections to one server.
- Information: the session exposes the protocol, cipher suite, peer certificates and creation and last-access times, which help in checking security.
- Security control: sessions can be invalidated (
invalidate()) and have timeouts, so keys are not reused forever. - Less load on servers that handle many clients.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Write program to compute square and Factorial of input number using RMI.
Answer
The client sends a number; the remote object returns its square and its factorial. For example, for 5 the square is and the factorial is .
Remote interface
import java.rmi.*;
public interface MathService extends Remote {
long square(int n) throws RemoteException;
long factorial(int n) throws RemoteException;
}
Implementation
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class MathServiceImpl extends UnicastRemoteObject implements MathService {
public MathServiceImpl() throws RemoteException { super(); }
public long square(int n) { return (long) n * n; }
public long factorial(int n) {
long f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
}
}
Server
import java.rmi.registry.*;
public class MathServer {
public static void main(String[] args) throws Exception {
Registry r = LocateRegistry.createRegistry(1099);
r.rebind("MathService", new MathServiceImpl());
System.out.println("Math server ready");
}
}
Client
import java.rmi.registry.*;
import java.util.Scanner;
public class MathClient {
public static void main(String[] args) throws Exception {
MathService m = (MathService) LocateRegistry.getRegistry("localhost", 1099).lookup("MathService");
System.out.print("Enter a number: ");
int n = new Scanner(System.in).nextInt();
System.out.println("Square = " + m.square(n));
System.out.println("Factorial = " + m.factorial(n));
}
}
Input 5 prints Square = 25 and Factorial = 120. A long overflows for .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is multicast group? Write the key operation of MulticastSocket
Answer
Multicast group
A multicast group is a set of hosts that have joined the same multicast IP address (class D, 224.0.0.0 to 239.255.255.255). A datagram sent to the group address is delivered to all current members. Hosts can join and leave at any time, and a sender need not be a member.
Key operations of MulticastSocket
MulticastSocket extends DatagramSocket and adds group features:
- Create:
new MulticastSocket(port)binds to a port to receive group traffic. joinGroup(InetAddress group): become a member, so the socket receives packets sent to that address.leaveGroup(InetAddress group): stop receiving packets for the group.send(DatagramPacket p): send a packet to the group address and port.receive(DatagramPacket p): wait for and read a packet from the group.setTimeToLive(int ttl)/getTimeToLive(): controls how many routers the packet may cross (1 keeps it on the local network).setInterface()/setNetworkInterface(): choose the network interface used.setLoopbackMode(): enables or disables receiving one's own multicasts.close(): release the socket.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What do you mean by socket address? Write the main method use in client socket.
Answer
Socket address
A socket address is the combination of an IP address and a port number (or a host name and port) that identifies one endpoint of a connection, for example 192.168.1.10:8080. In Java it is represented by the abstract class java.net.SocketAddress, whose concrete subclass is InetSocketAddress.
Creating one: new InetSocketAddress("www.example.com", 80), new InetSocketAddress(InetAddress, port), or new InetSocketAddress(port) for a wildcard local address. Its methods include getAddress(), getHostName(), getPort() and isUnresolved(). It is used with connect(), bind() and DatagramPacket, and socket.getRemoteSocketAddress() returns the peer's address.
Main methods used in a client socket (Socket)
- Constructors:
Socket(String host, int port),Socket(InetAddress addr, int port)andSocket(). connect(SocketAddress addr)andconnect(addr, timeout): open the connection.getInputStream(): stream for reading data from the server.getOutputStream(): stream for writing data to the server.close(): closes the socket.isConnected(),isClosed(): state tests.getInetAddress(),getPort(),getLocalPort(),getLocalAddress(): connection information.setSoTimeout(),setTcpNoDelay(),setKeepAlive(),setSoLinger(): socket options.shutdownInput()andshutdownOutput(): close one direction only.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 2+4+4 marks
Explain the concept of sockets in Java and describe how a client communicates with a server using sockets give example.
Answer
Concept of sockets in Java
A socket is an endpoint of a two-way communication link between two programs on a network, identified by an IP address and a port number. Java supports TCP sockets through java.net.Socket (client side) and java.net.ServerSocket (server side), and UDP through DatagramSocket. TCP sockets give a reliable, ordered, connection-oriented byte stream, and the program reads and writes it like any other I/O stream. Secure sockets are provided by SSLSocket.
How a client communicates with a server
- The server creates a
ServerSocketon a port and callsaccept(), which blocks until a client connects. - The client creates a
Socketwith the server's host and port. The TCP three-way handshake takes place andaccept()returns aSocketfor that client. - Both sides obtain input and output streams from their sockets (
getInputStream(),getOutputStream()). - They exchange data: what one side writes, the other reads.
- Either side closes the socket, which ends the connection.
Example: the client sends a name and the server replies with a greeting
Server
import java.io.*;
import java.net.*;
public class GreetServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5000);
System.out.println("Server waiting...");
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
String name = in.readLine();
out.println("Hello, " + name + "! Welcome.");
s.close();
ss.close();
}
}
Client
import java.io.*;
import java.net.*;
public class GreetClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("Ram");
System.out.println(in.readLine()); // Hello, Ram! Welcome.
s.close();
}
}
The server is started first and waits; the client then connects, sends "Ram" and prints the reply. The server can be made to serve many clients by handing each accepted socket to a new thread.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5+5 marks
Explain the URLConnection class and its role in retrieving data from web servers with example.
Answer
URLConnection class
java.net.URLConnection is an abstract class in the java.net package. It represents a communication link between a Java application and a resource named by a URL. It is more powerful than URL.openStream() because it lets the program inspect response headers, set request headers, choose between input and output, and control timeouts and caching. For http:// and https:// URLs the object returned is actually a subclass, HttpURLConnection (or HttpsURLConnection), which adds the request method, status code and redirect handling.
Role in retrieving data from web servers
URLConnection separates the work of fetching a resource into distinct phases:
- Create the URL:
URL url = new URL("http://example.com/index.html"); - Obtain the connection:
URLConnection conn = url.openConnection();This creates the object but does not yet contact the server. - Configure the request (before connecting):
setRequestProperty("User-Agent", ...),setConnectTimeout(ms),setReadTimeout(ms),setDoOutput(true)(for POST),setUseCaches(false). - Connect:
conn.connect()opens the network connection. It is called implicitly by the first method that needs the response. - Read the response header:
getContentType(),getContentLength(),getContentEncoding(),getDate(),getLastModified(),getHeaderField(name). - Read the body:
conn.getInputStream()returns the stream from which the data is read. - Send data (optional):
conn.getOutputStream()is used to send a request body such as form data in a POST.
Because the request is configured before the connection is made, the application can send cookies, authorisation and language headers, and decide how to handle the data (text or binary) from the content type returned.
Example: reading a web page and its headers
import java.io.*;
import java.net.*;
public class URLConnectionDemo {
public static void main(String[] args) throws IOException {
URL url = new URL("http://example.com/");
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
// Header information
System.out.println("Content-Type : " + conn.getContentType());
System.out.println("Content-Length: " + conn.getContentLength());
System.out.println("Last-Modified : " + conn.getLastModified());
// Body
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
}
}
The program creates the connection, sets timeouts and a header, prints header fields, then reads the HTML line by line.
Example: sending data (POST)
HttpURLConnection http = (HttpURLConnection) new URL("http://example.com/login").openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
try (OutputStream os = http.getOutputStream()) {
os.write("user=ram&pass=1234".getBytes("UTF-8"));
}
System.out.println("Status: " + http.getResponseCode());
Summary: URLConnection gives protocol-independent, fine-grained control over a request/response exchange. It is the base for fetching web pages, downloading files and calling web services from Java.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 2+4+4 marks
Write the difference between blocking I/O and Non-blocking I/O? Explain the basic mechanism of handling Buffer and channels in java with example.
Answer
Difference between blocking and non-blocking I/O
| Blocking I/O (java.io, standard sockets) | Non-blocking I/O (java.nio) |
|---|---|
A call such as read() or accept() suspends the thread until data or a connection is available. | The call returns immediately; it gives whatever is available (possibly nothing). |
| Needs one thread per connection, so many clients mean many threads and high memory and context-switch cost. | One thread can manage many channels using a Selector. |
| Stream-oriented: data is read byte by byte in one direction. | Buffer-oriented: data is read into and written from buffers, and can be moved back and forth. |
| Simple to program. | More complex, but scalable for servers with thousands of connections. |
Streams are one-way (InputStream or OutputStream). | Channels are two-way. |
Buffers and channels in Java NIO
Channel: a Channel (package java.nio.channels) is a connection to an entity such as a file or socket through which data is read or written. Examples are FileChannel, SocketChannel, ServerSocketChannel and DatagramChannel. Channels are bidirectional, can be put in non-blocking mode (configureBlocking(false)) and always transfer data to or from a Buffer; data is never read or written to a channel directly.
Buffer: a Buffer (package java.nio) is a fixed-size block of memory that holds data of one primitive type (ByteBuffer, CharBuffer, IntBuffer, ...). It has four key properties:
- capacity: maximum number of elements.
- position: index of the next element to read or write.
- limit: first index that must not be read or written.
- mark: a remembered position, restored by
reset().
The invariant is .
Mechanism of use:
- Allocate a buffer:
ByteBuffer.allocate(1024). - Read from the channel into the buffer (
channel.read(buf)); the buffer is in write mode and position advances. - Call
buf.flip(), which sets limit = position and position = 0, switching to read mode. - Read the data from the buffer (
buf.get()) or write it to another channel (channel.write(buf)). - Call
buf.clear()(orcompact()) to prepare for the next read.
Example: copying a file with channels and a buffer
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelCopy {
public static void main(String[] args) throws IOException {
try (FileChannel in = new FileInputStream("source.txt").getChannel();
FileChannel out = new FileOutputStream("copy.txt").getChannel()) {
ByteBuffer buf = ByteBuffer.allocate(1024);
while (in.read(buf) != -1) { // channel -> buffer
buf.flip(); // switch to read mode
out.write(buf); // buffer -> channel
buf.clear(); // ready for next read
}
}
System.out.println("File copied.");
}
}
In a non-blocking server, a SocketChannel is set with configureBlocking(false) and registered with a Selector; the single thread calls selector.select() and handles only those channels that are ready for accept, read or write, reading each into a ByteBuffer.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BCA 2021 Sixth Semester Applied Economics (TU board exam, 2021), TU BCA 2022 Sixth Semester Applied Economics (TU board exam, 2022), TU BCA 2023 Sixth Semester Applied Economics (TU board exam, 2023), TU BCA 2024 Sixth Semester Applied Economics (TU board exam, 2024), TU BCA 2025 Sixth Semester Applied Economics (TU board exam, 2025), TU BCA 2026 Sixth Semester Applied Economics (TU board exam, 2026), TU BCA 2021 Sixth Semester Distributed System (TU board exam, 2021), TU BCA 2022 Sixth Semester Distributed System (TU board exam, 2022), TU BCA 2023 Sixth Semester Distributed System (TU board exam, 2023), TU BCA 2024 Sixth Semester Distributed System (TU board exam, 2024), TU BCA 2025 Sixth Semester Distributed System (TU board exam, 2025), TU BCA 2026 Sixth Semester Distributed System (TU board exam, 2026), TU BCA 2021 Sixth Semester Advanced Java Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Advanced Java Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Advanced Java Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Advanced Java Programming (TU board exam, 2024), TU BCA 2025 Sixth Semester Advanced Java Programming (TU board exam, 2025), TU BCA 2026 Sixth Semester Advanced Java Programming (TU board exam, 2026), TU BCA 2021 Sixth Semester Mobile Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Mobile Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Mobile Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Mobile Programming (TU board exam, 2024), TU BCA 2025 Sixth Semester Mobile Programming (TU board exam, 2025), TU BCA 2026 Sixth Semester Mobile Programming (TU board exam, 2026), TU BCA 2021 Sixth Semester Network Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Network Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Network Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Network Programming (TU board exam, 2024) and TU BCA 2025 Sixth Semester Network Programming (TU board exam, 2025). Answers are written for this site; check them against your class notes.