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

Network Programming Lab Report

This document is a lab report for a course on Network Programming at Tribhuvan University, detailing various programming tasks related to network operations in Java. It includes a table of contents listing 32 programming assignments, each focusing on different aspects of network programming such as IP address resolution, URL handling, and socket communication. The report is submitted by a student in partial fulfillment of their Bachelor's degree in Computer Application.

Uploaded by

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

Network Programming Lab Report

This document is a lab report for a course on Network Programming at Tribhuvan University, detailing various programming tasks related to network operations in Java. It includes a table of contents listing 32 programming assignments, each focusing on different aspects of network programming such as IP address resolution, URL handling, and socket communication. The report is submitted by a student in partial fulfillment of their Bachelor's degree in Computer Application.

Uploaded by

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

TRIBHUVAN UNIVERSITY

FACULTY OF HUMANITIES AND SOCIAL SCIENCES

LAB REPORT ON

Network Programming (CACS355)

Submitted to:

Department of Computer Application

Mechi Multiple Campus

Bhadrapur, Jhapa

In partial fulfillment of the requirements for the Bachelors in

Computer Application

Submitted By:

Gagan Jung Gurung (Roll No:16)

BCA 6th Semester

Under the Supervision of

Karna Tamang
TABLE OF CONTENTS

[Link] a program that print the address of [Link] ..................................... 1

[Link] a program that finds the address of the local machine. ....................................... 1

[Link] a program that find the canonical hostname of a given address. ...................... 2

[Link] a program to find the IP address and host name of the local machine. .............. 2

[Link] a program to get IPV4 and IPV6 address of a given web address. ..................... 3

[Link] a program for Determining whether an IP address is IPV4 and IPV6. ............... 3

[Link] a program that splits the parts of a URL (Splitting URL into pieces information.
.......................................................................................................................................... 4

8. Write a program that checks the which protocols does a virtual machine support or
Not? .................................................................................................................................. 5

[Link] a program to download a web page of a given address. ..................................... 6

10. Write a program for resolving Relative URL ............................................................ 7

11. Write a program to download an object ..................................................................... 8

12. Write a program that communicate with Server- side program through GET. ......... 9

13. Write a program that shows a simple CookiePolicy that blocks cookies from .gov
domains. ......................................................................................................................... 11

14. Write a program to download a web page using URLConnection. ......................... 13

15. Write a program to read value of HTTP header Fields. ........................................... 14

16. Write a program to print the entire HTTP header. ................................................... 15

17. Write a program for HTTP Request Methods.......................................................... 17

18. Write a program to print the URL of a URLConnection to "[Link]" .. 18

19. Write a program to get the time when a URL was last changed.............................. 19

20. Write a program reading from servers with socket .................................................. 20

21. Write a program writing from servers with socket. ................................................. 21

22. Write a program socket to read Time Client. ........................................................... 22

23. Write a program socket to Low Port Scanner. ....................................................... 23


24. Write a program socket to SocketInfo. .................................................................... 24

25. Write a program socket for a server. ........................................................................ 25

26. Write a program for Secure Socket with – [Link] ...................................... 27

27. Write a program to input two numbers and calculate addition of two numbers by
using client and server RMI ........................................................................................... 28

[Link] a program for reading input from a Socket: .................................................. 29

The following fragment connect to the daytime server on port13 of the [Link]
and display the data it’s sent timeClient ........................................................................ 29

[Link] a program in java for getting a socket’s information. ................................... 31

30. Write a program for Reading Data with a ServerSocket: ........................................ 32

[Link] a program in java to display Date and time .................................................... 33

[Link] a program for ServerSocket ............................................................................ 34


[Link] a program that print the address of [Link]
import [Link];
class Main {
public static void main(String[] args) {
try {
InetAddress address = [Link]("[Link]");
[Link]("Host Name: " + [Link]());
[Link]("IP Address: " + [Link]());
} catch (Exception e) {
[Link]("Error: " + e);
}
}
}
[Link] a program that finds the address of the local machine.
import [Link];

public class Main {


public static void main(String[] args) {
try {
// Get the local host address information
InetAddress localHost = [Link]();

// Print the computer's name and its IP address


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

} catch (Exception e) {
// Handle cases where the local host cannot be resolved
[Link]("Error: " + e);
}
}
}

1
[Link] a program that find the canonical hostname of a given address.
import [Link];

public class Main {


public static void main(String[] args) {
try {
// Looking up a specific web address
InetAddress address = [Link]("[Link]");

// Displaying the IP and the official name


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

} catch (Exception e) {
// Catches UnknownHostException if the URL is wrong or internet is down
[Link]("Error: " + e);
}
}
}
[Link] a program to find the IP address and host name of the local machine.
import [Link];
public class Main {
public static void main(String[] args) {
try {
// Get the local host details
InetAddress localHost = [Link]();
// Print the computer's name and its network IP
[Link]("Host Name: " + [Link]());
[Link]("IP Address: " + [Link]());
} catch (Exception e) {
// Handle cases where the network card is disabled or hostname is invalid
[Link]("Error: " + e);
}

2
}
}
[Link] a program to get IPV4 and IPV6 address of a given web address.
import [Link];

public class Main {


public static void main(String[] args) {
try {
// Define the host we want to look up
String host = "[Link]";

// getAllByName returns an array because one domain


// can be linked to multiple IP addresses
InetAddress[] addresses = [Link](host);

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

// Loop through the array to print every associated IP


for (InetAddress addr : addresses) {
[Link]("IP Address: " + [Link]());
}

} catch (Exception e) {
// Catches UnknownHostException if the site is down or name is invalid
[Link]("Error: " + e);
}
}
}
[Link] a program for Determining whether an IP address is IPV4 and IPV6.
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {

3
Scanner sc = new Scanner([Link]);
[Link]("Enter an IP address: ");
String ip = [Link]();
try {
// Convert string input into an InetAddress object
InetAddress address = [Link](ip);
// Check for ":" to identify IPv6 or "." for IPv4
if ([Link]().contains(":")) {
[Link](ip + " is an IPv6 address.");
} else if ([Link]().contains(".")) {
[Link](ip + " is an IPv4 address.");
}
} catch (Exception e) {
// This triggers if the input isn't a valid IP or host
[Link]("Invalid IP address.");
} finally {
[Link]();
}
}
}
[Link] a program that splits the parts of a URL (Splitting URL into pieces
information.
import [Link];

public class Main {


public static void main(String[] args) {
try {
// Define a complex URL with various components
URL url = new URL
("[Link]

// Extract and print each part of the URL


[Link]("Full URL : " + [Link]());

4
[Link]("Protocol : " + [Link]());
[Link]("Host Name : " + [Link]());
[Link]("Port Number : " + [Link]());
[Link]("Path : " + [Link]());
[Link]("File : " + [Link]());
[Link]("Query : " + [Link]());
[Link]("Reference : " + [Link]());

} catch (Exception e) {
// Triggers if the URL string is malformed
[Link]("Invalid URL");
}
}
}
8. Write a program that checks the which protocols does a virtual machine support
or Not?
import [Link];
import [Link];
import [Link];
import [Link];

public class ProtocolChecker {

// Attempts to open a TCP Server Socket


public static void checkTCP(int port) {
try (ServerSocket serverSocket = new ServerSocket(port)) {
[Link]("TCP protocol: Supported ✅");
} catch (IOException e) {
[Link]("TCP protocol: NOT supported or Port in use ❌");
}
}

// Attempts to open a UDP Datagram Socket


public static void checkUDP(int port) {
try (DatagramSocket ds = new DatagramSocket(port)) {
[Link]("UDP protocol: Supported ✅");
} catch (SocketException e) {
[Link]("UDP protocol: NOT supported or Port in use ❌");
}

5
}

public static void main(String[] args) {


int testPort = 9999; // A standard high-numbered port often used for testing

[Link]("Checking protocol support on this machine...\n");

checkTCP(testPort);
checkUDP(testPort);
}
}
[Link] a program to download a web page of a given address.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class WebPageDownloader {


public static void main(String[] args) {
// Target website URL
String webAddress = "[Link]
try {
// 1. Create the URL and open the connection
URL url = new URL(webAddress);
HttpURLConnection connection = (HttpURLConnection) [Link]();

// 2. Set the HTTP method (GET is default, but good to be explicit)


[Link]("GET");

// 3. Check if the server responded successfully (HTTP 200)


int responseCode = [Link]();
if (responseCode == HttpURLConnection.HTTP_OK) {

// 4. Create a stream reader to capture the response


BufferedReader reader = new BufferedReader(

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

String line;
[Link]("Downloading content from: " + webAddress + "\n");

// 5. Read the content line by line and print to console


while ((line = [Link]()) != null) {
[Link](line);
}
// 6. Close the resources
[Link]();
} else {
[Link]("Failed to connect. HTTP response code: " + responseCode);
}
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
10. Write a program for resolving Relative URL
import [Link];
import [Link];
public class RelativeURLResolverTU {
public static void main(String[] args) {
try {
// 1. Define the Base URL (The starting point)
URL baseURL = new URL("[Link]

// 2. List of relative paths to resolve


String[] relativePaths = {
"[Link]", // Simple file in current directory
"departments/[Link]", // Sub-directory path

7
"../images/[Link]", // Go up one level, then into images
"./[Link]" // Explicitly stay in current directory
};

[Link]("Base URL: " + baseURL + "\n");

// 3. Resolve each relative URL against the Base URL


for (String rel : relativePaths) {
// The URL constructor handles the logic of merging paths
URL absoluteURL = new URL(baseURL, rel);

[Link]("Relative URL: " + rel);


[Link]("Resolved Absolute URL: " + absoluteURL + "\n");
}

} catch (MalformedURLException e) {
[Link]("Error: " + [Link]());
}
}
}

11. Write a program to download an object


import [Link];
import [Link];
import [Link];
import [Link];

public class GoogleDownloader {


public static void main(String[] args) {
String fileURL = "[Link]
String saveAs = "google_homepage.html";

// Try-with-resources ensures streams are closed automatically

8
try (BufferedInputStream in = new BufferedInputStream(new
URL(fileURL).openStream());
FileOutputStream out = new FileOutputStream(saveAs)) {

byte[] buffer = new byte[1024]; // 1KB buffer size


int bytesRead;

// Read from the URL and write to the local file


while ((bytesRead = [Link](buffer, 0, 1024)) != -1) {
[Link](buffer, 0, bytesRead);
}

[Link]("Google homepage downloaded successfully as: " + saveAs);

} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
12. Write a program that communicate with Server- side program through GET.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class FacebookGetClient {


public static void main(String[] args) {
try {
// 1. Set the target URL
String serverURL = "[Link]
URL url = new URL(serverURL);

9
// 2. Open the connection
HttpURLConnection connection = (HttpURLConnection) [Link]();

// 3. Set the request method


[Link]("GET");

// 4. CRITICAL: Set User-Agent to mimic a real web browser


// Without this, many servers will return a 403 Forbidden error
[Link]("User-Agent", "Mozilla/5.0");

// 5. Get and print the response status


int responseCode = [Link]();
[Link]("Sending GET request to: " + serverURL);
[Link]("Response Code: " + responseCode);

// 6. Handle the response data


if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]())
);

String inputLine;
StringBuilder response = new StringBuilder();

// Build the string line by line


while ((inputLine = [Link]()) != null) {
[Link](inputLine).append("\n");
}
[Link]();

[Link]("\nResponse Content Preview:");


[Link]([Link]().substring(0, 500) + "...");
// Just a preview
} else {
10
[Link]("GET request failed.");
}

} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
13. Write a program that shows a simple CookiePolicy that blocks cookies from .gov
domains.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class GovCookieBlocker {


public static void main(String[] args) {
// 1. Create a custom CookiePolicy that blocks .gov domains
CookiePolicy blockGovPolicy = new CookiePolicy() {
@Override
public boolean shouldAccept(URI uri, HttpCookie cookie) {
if ([Link]().endsWith(".gov")) {
[Link]("Blocking cookie from: " + [Link]() + " | Cookie: " +
cookie);
return false; // Reject cookies from .gov domains
} else {
[Link]("Accepting cookie from: " + [Link]() + " | Cookie: " +
cookie);
return true; // Accept cookies from all other domains
}
}

11
};

// 2. Set up the global CookieManager with our custom policy


CookieManager cookieManager = new CookieManager();
[Link](blockGovPolicy);

// 3. Make this the default manager for all future network connections
[Link](cookieManager);

try {
// 4. Create example URIs and cookies for testing
URI govURI = new URI("[Link]
URI eduURI = new URI("[Link]

HttpCookie govCookie = new HttpCookie("govTest", "12345");


HttpCookie eduCookie = new HttpCookie("eduTest", "67890");

// 5. Attempt to add cookies to the store


// The Manager will consult the Policy before adding them
[Link]().add(govURI, govCookie);
[Link]().add(eduURI, eduCookie);

// 6. Verify which cookies actually made it into the store


List<HttpCookie> acceptedCookies =
[Link]().getCookies();
[Link]("\nAccepted cookies in store:");
for (HttpCookie c : acceptedCookies) {
[Link](c);
}
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
12
14. Write a program to download a web page using URLConnection.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class GooglePageDownloader {


public static void main(String[] args) {
try {
// 1. Specify the target URL
String webAddress = "[Link]
URL url = new URL(webAddress);

// 2. Open the connection and set headers


URLConnection connection = [Link]();
[Link]("User-Agent", "Mozilla/5.0");

// 3. Set up the input stream to read from the web


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

// 4. Set up the output stream to write to a local file


FileWriter writer = new FileWriter("google_homepage.html");

// 5. Read line-by-line and write to the file


String line;
while ((line = [Link]()) != null) {
[Link](line + "\n");
}

// 6. Close all resources to prevent memory leaks


13
[Link]();
[Link]();

[Link]("Google homepage downloaded successfully as


google_homepage.html");

} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
15. Write a program to read value of HTTP header Fields.
import [Link];
import [Link];
import [Link];
import [Link];

public class ReadHTTPHeaders {


public static void main(String[] args) {
try {
// 1. Specify the URL
URL url = new URL("[Link]

// 2. Open the connection and set client properties


URLConnection connection = [Link]();
[Link]("User-Agent", "Mozilla/5.0");

// 3. Establish the actual network connection


[Link]();

// 4. Retrieve the headers into a Map


// Map keys are the header names (e.g., "Content-Type")
// Map values are Lists because a header can have multiple values

14
Map<String, List<String>> headerFields = [Link]();

[Link]("HTTP Header Fields:\n");

// 5. Iterate through the map and print each key-value pair


for ([Link]<String, List<String>> entry : [Link]()) {
String headerName = [Link]();
List<String> headerValues = [Link]();

// Note: The 'null' key usually contains the HTTP Status Line
[Link]((headerName == null ? "Status Line" : headerName) + " : " +
headerValues);
}

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
16. Write a program to print the entire HTTP header.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class PrintHTTPHeader {


public static void main(String[] args) {
try {
// 1. Target URL
String webAddress = "[Link]
URL url = new URL(webAddress);

15
// 2. Open HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) [Link]();

// 3. Configure request settings


[Link]("GET");
[Link]("User-Agent", "Mozilla/5.0");

// 4. Establish connection
[Link]();

// 5. Retrieve all header fields


Map<String, List<String>> headerFields = [Link]();

[Link]("=== HTTP Header Fields for " + webAddress + " ===\n");

// 6. Iterate and print headers


for ([Link]<String, List<String>> entry : [Link]()) {
String headerName = [Link]();
List<String> headerValues = [Link]();

// If headerName is null, it represents the Status Line (e.g., HTTP/1.1 200 OK)
String displayName = (headerName == null) ? "Status-Line" : headerName;
[Link](displayName + " : " + headerValues);
}

} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}

16
17. Write a program for HTTP Request Methods.
import [Link];
import [Link];
import [Link];

public class HTTPRequestMethodsDemo {


public static void main(String[] args) {
// Free test server that echoes back whatever you send it
String targetURL = "[Link]

// 1. GET: Fetch data


sendRequest(targetURL + "/get", "GET");

// 2. POST: Create new data


sendRequest(targetURL + "/post", "POST");

// 3. PUT: Update existing data


sendRequest(targetURL + "/put", "PUT");

// 4. DELETE: Remove data


sendRequest(targetURL + "/delete", "DELETE");
}

public static void sendRequest(String urlStr, String method) {


try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) [Link]();
[Link](method);
[Link]("User-Agent", "Mozilla/5.0");

// For POST/PUT, we need to send a 'Body' (payload)


if ([Link]("POST") || [Link]("PUT")) {
[Link](true); // Allows sending data
String data = "name=Karna&age=25";
17
try (OutputStream os = [Link]()) {
[Link]([Link]());
[Link]();
}
}

int responseCode = [Link]();


[Link]("\nHTTP " + method + " Request to " + urlStr);
[Link]("Response Code: " + responseCode);

} catch (Exception e) {
[Link]("Error (" + method + "): " + [Link]());
}
}
}
18. Write a program to print the URL of a URLConnection to "[Link]"
import [Link];
import [Link];

public class URLConnectionURL {


public static void main(String[] args) {
try {
// 1. Define the target website
String webAddress = "[Link]
URL url = new URL(webAddress);

// 2. Open the URL connection


// This creates a communication link but doesn't connect yet
URLConnection connection = [Link]();

// 3. Use getURL() to retrieve the URL associated with this connection


[Link]("URLConnection URL: " + [Link]());

18
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
19. Write a program to get the time when a URL was last changed.
import [Link];
import [Link];
import [Link];
import [Link];

public class URLLastModified {


public static void main(String[] args) {
try {
// 1. Target URL
String webAddress = "[Link]
URL url = new URL(webAddress);

// 2. Open connection
URLConnection connection = [Link]();

// 3. Get the last modified timestamp (returned in milliseconds since epoch)


long lastModified = [Link]();

if (lastModified == 0) {
// Some servers disable this header for security or dynamic content
[Link]("The server did not provide Last-Modified information.");
} else {
// 4. Convert the 'long' timestamp into a readable Date object
Date lastModifiedDate = new Date(lastModified);

// 5. Format the date into a human-friendly string

19
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy
HH:mm:ss z");

[Link]("Last-Modified time of " + webAddress + " : " +


[Link](lastModifiedDate));
}
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
20. Write a program reading from servers with socket
import [Link];
import [Link];
import [Link];
import [Link];

public class SocketReadServer {


public static void main(String[] args) {
String server = "[Link]";
int port = 80; // Standard HTTP port

// Use try-with-resources to automatically close the socket and streams


try (Socket socket = new Socket(server, port);
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()))) {

// 1. Manually construct the HTTP GET request


[Link]("GET / HTTP/1.1");
[Link]("Host: " + server);
[Link]("Connection: Close");
[Link](); // Crucial: A blank line tells the server the request is finished

20
// 2. Read and print the raw response (Headers + HTML)
[Link]("Response from server:\n");
String line;
while ((line = [Link]()) != null) {
[Link](line);
}

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
21. Write a program writing from servers with socket.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SocketWriteServer {


public static void main(String[] args) {
String server = "[Link]";
int port = 80;

try (Socket socket = new Socket(server, port);


PrintWriter out = new PrintWriter(new
OutputStreamWriter([Link]()), true);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()))) {

// 1. Data to be sent in the request body


String data = "name=Karna&age=25";

21
// 2. Construct the HTTP POST request manually
[Link]("POST /post HTTP/1.1");
[Link]("Host: " + server);
[Link]("User-Agent: Java Socket Client");
[Link]("Content-Type: application/x-www-form-urlencoded");

// Crucial: Server needs to know the size of the body data


[Link]("Content-Length: " + [Link]());
[Link]("Connection: Close");

// 3. Blank line to separate Headers from the Body


[Link]();

// 4. Send the actual payload


[Link](data);

// 5. Read the response


[Link]("Response from server:\n");
String line;
while ((line = [Link]()) != null) {
[Link](line);
}

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
22. Write a program socket to read Time Client.
import [Link];
import [Link];
import [Link];

22
public class TimeClient {
public static void main(String[] args) {
// public-facing server provided by NIST
String server = "[Link]";
// Port 13 is the standard port for the Daytime Protocol
int port = 13;

try (Socket socket = new Socket(server, port);


BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]()))) {

[Link]("Time from server (" + server + "):");

// The server sends one or more lines of text and then disconnects
String time;
while ((time = [Link]()) != null) {
if ([Link]() > 0) {
[Link](time);
}
}

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
23. Write a program socket to Low Port Scanner.
import [Link];

public class LowPortScanner {


public static void main(String[] args) {
String host = "localhost"; // The machine being scanned

23
[Link]("Scanning low ports on: " + host);
[Link]("Checking Ports 1 to 1024...\n");

for (int port = 1; port <= 1024; port++) {


try {
// Attempt to establish a TCP connection
Socket socket = new Socket(host, port);

// If the line above doesn't throw an exception, the port is open


[Link]("Port " + port + " is OPEN ✅");

// Always close the socket once the test is done


[Link]();
} catch (Exception e) {
// If an exception occurs, the port is likely closed or blocked
// We do nothing here and move to the next port
}
}
[Link]("\nScan completed.");
}
}
24. Write a program socket to SocketInfo.
import [Link];
import [Link];

public class SocketInfo {


public static void main(String[] args) {
try {
// 1. Establish a connection to the remote server
Socket socket = new Socket("[Link]", 80);

// 2. Extract the InetAddress object from the socket


InetAddress inetAddress = [Link]();

24
[Link]("=== Socket Information ===");

// Remote details (The Server)


[Link]("Remote Host Name : " + [Link]());
[Link]("Remote Host IP : " + [Link]());
[Link]("Remote Port : " + [Link]());

// Local details (Your Machine)


[Link]("Local Address : " + [Link]());
[Link]("Local Port : " + [Link]());

// 3. Close the connection


[Link]();

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
25. Write a program socket for a server.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SimpleServer {


public static void main(String[] args) {
int port = 5000; // The "door number" the server listens on

try (ServerSocket serverSocket = new ServerSocket(port)) {


[Link]("Server started on port " + port);

25
[Link]("Waiting for client connection...");

// 1. BLOCKING CALL: The program pauses here until a client connects


Socket clientSocket = [Link]();
[Link]("Client connected from " + [Link]());

// 2. Setup communication streams


BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);

String clientMessage;
// 3. Keep reading until the client stops sending data
while ((clientMessage = [Link]()) != null) {
[Link]("Client says: " + clientMessage);

// 4. Send a response back to the client


[Link]("Server received: " + clientMessage);

// 5. Termination condition
if ([Link]("bye")) {
[Link]("Client disconnected.");
break;
}
}

[Link]();
[Link]("Server stopped.");

} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
26
26. Write a program for Secure Socket with – [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SecureSocketClient {


public static void main(String[] args) {
String host = "[Link]";
int port = 443; // Standard port for HTTPS (SSL/TLS)

try {
// 1. Obtain the default SSLSocketFactory
SSLSocketFactory factory = (SSLSocketFactory) [Link]();

// 2. Create a secure socket and connect to the host


// This automatically handles the SSL/TLS Handshake
SSLSocket socket = (SSLSocket) [Link](host, port);
[Link]("Connected to " + host + " via secure socket ✅");

// 3. Setup output to send an encrypted HTTPS request


PrintWriter out = new PrintWriter([Link](), true);
[Link]("GET / HTTP/1.1");
[Link]("Host: " + host);
[Link]("User-Agent: Java SSLSocket Client");
[Link]("Connection: Close");
[Link](); // Signal end of headers

// 4. Setup input to read the decrypted response from the server


BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String line;

27
[Link]("\nResponse from server:\n");

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


[Link](line);
}

// 5. Cleanup
[Link]();
[Link]();
[Link]();

} catch (Exception e) {
[Link]("Security Error: " + [Link]());
}
}
}
27. Write a program to input two numbers and calculate addition of two numbers by
using client and server RMI
import [Link];
import [Link];
import [Link];

// 1. The Server implementation class


public class CalculatorServer extends UnicastRemoteObject implements Calculator {

protected CalculatorServer() throws RemoteException {


super();
}

// 2. Implementation of the remote method


@Override
public int add(int a, int b) throws RemoteException {
[Link]("Server is adding: " + a + " + " + b);

28
return a + b;
}

public static void main(String[] args) {


try {
// 3. Create the remote object instance
CalculatorServer obj = new CalculatorServer();

// 4. Register the object with the RMI Registry


// The Registry acts like a phonebook for distributed objects
[Link]("rmi://localhost:1099/CalculatorService", obj);

[Link]("Calculator RMI Server is ready...");

} catch (Exception e) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}
[Link] a program for reading input from a Socket:
The following fragment connect to the daytime server on port13 of the [Link]
and display the data it’s sent timeClient
import [Link].*;
import [Link].*;
import [Link];
import [Link];
import [Link];

public class TimeClient {


public static void main(String[] args) {
String server = "[Link]";
int port = 13;

29
try (Socket socket = new Socket(server, port);
// Explicitly use ASCII encoding as per NIST protocol standards
BufferedReader br = new BufferedReader(new
InputStreamReader([Link](), "ASCII"))) {

String line;
while ((line = [Link]()) != null) {
// Skip the blank line often sent at the start of NIST responses
if ([Link]().isEmpty()) continue;

[Link]("Server Time String: " + line);

// 1. Split the string by spaces to isolate components


String[] parts = [Link](" ");

if ([Link] >= 3) {
String datePart = parts[1]; // Index 1: yy-MM-dd
String timePart = parts[2]; // Index 2: HH:mm:ss
String dateTimeStr = datePart + " " + timePart;

// 2. Define the parser matching NIST's specific format


SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");

try {
// 3. Convert String -> Date Object
Date nistDate = [Link](dateTimeStr);
[Link]("Parsed NIST Time: " + nistDate);
} catch (ParseException pe) {
[Link]("Could not parse NIST time.");
}
}
}

30
// 4. Comparison with local clock
[Link]("Local System Time: " + new Date());

} catch (IOException e) {
[Link]("Connection error: " + e);
}
}
}
[Link] a program in java for getting a socket’s information.
import [Link];
import [Link];
import [Link];
import [Link];

public class LocalPortScanner {


public static void main(String[] args) {
try {
// 1. Identify the local machine's network information
InetAddress local = [Link]();
String hostname = [Link]();

[Link]("Scanning ALL ports on host: " + hostname + " (" +


[Link]() + ")");

// 2. Scan the full range of TCP ports (1 to 65535)


for (int port = 1; port <= 65535; port++) {
// Try-with-resources ensures the socket closes immediately if it connects
try (Socket socket = new Socket(local, port)) {
[Link]("✅ A server is listening on port " + port);
} catch (IOException ex) {
// Port is closed, refused, or timed out; ignore and move to next
}
}

31
[Link]("Port scan completed.");

} catch (UnknownHostException e) {
[Link]("Cannot resolve local host: " + e);
}
}
}
30. Write a program for Reading Data with a ServerSocket:
(Server Program)
import [Link].*;
import [Link].*;

public class ServerSocketProgram {


public static void main(String[] args) {
try {
// Create a server socket on port 2430
ServerSocket ss = new ServerSocket(2430);
[Link]("Server is waiting for a client...");

// accept() blocks until a client connects


Socket s = [Link]();
[Link]("Client connected!");

// Wrap the output stream to send text


BufferedWriter out = new BufferedWriter(new
OutputStreamWriter([Link]()));

[Link]("Hello, I am server\n");
[Link](); // Ensure data is actually sent over the wire

[Link](); // Close connection


[Link](); // Close server
} catch (IOException e) {

32
[Link](e);
}
}
}
(Client Program)
import [Link].*;
import [Link].*;

public class ClientServerFetch {


public static void main(String[] args) {
try {
// Connect to the server running on the local machine at port 2430
Socket s = new Socket("localhost", 2430);

// Set up a BufferedReader to read the text sent by the server


InputStream in = [Link]();
BufferedReader br = new BufferedReader(new InputStreamReader(in));

// Use Java 8+ Streams to print all lines received


[Link]().forEach([Link]::println);

[Link]();
} catch (IOException e) {
[Link]();
}
}
}
[Link] a program in java to display Date and time
import [Link].*;
import [Link].*;
import [Link];

public class DaytimeServer {

33
public final static int PORT = 2430;

public static void main(String[] args) {


// 1. Initialize the ServerSocket
try (ServerSocket server = new ServerSocket(PORT)) {
[Link]("Server started on port " + PORT + ". Waiting for clients...");

// 2. The Infinite Loop: Keep the server running forever


while (true) {
// 3. Wait for a connection (Blocking call)
try (Socket client = [Link]()) {
[Link]("Client connected: " + [Link]());

// 4. Send the data to the client


try (Writer out = new OutputStreamWriter([Link]())) {
[Link]("I am a server:\n");
Date now = new Date();
[Link]("Date and time: " + [Link]() + "\n");
[Link](); // Ensure data is sent
}
// 5. Client socket is automatically closed by try-with-resources
} catch (IOException e) {
[Link]("Error handling client: " + [Link]());
}
}
} catch (IOException ex) {
[Link]("Server error: " + [Link]());
}
}
}

[Link] a program for ServerSocket


import [Link].*;

34
import [Link].*;
import [Link];

public class ServerSocketProgram {


public static final int PORT = 13; // Daytime port

public static void main(String[] args) {


try (ServerSocket ss = new ServerSocket(PORT)) {
[Link]("Multi-threaded Server started on port " + PORT);

while (true) {
// 1. Listen for a new connection
Socket clientSocket = [Link]();
[Link]("Client connected: " + [Link]());

// 2. Hand the connection to a NEW thread and start it immediately


Thread task = new DaytimeThread(clientSocket);
[Link]();

// 3. The loop restarts instantly to handle the next client


}
} catch (IOException ex) {
[Link]("Server error: " + [Link]());
}
}

// Inner class to handle individual client conversations


private static class DaytimeThread extends Thread {
private Socket connection;

DaytimeThread(Socket connection) {
[Link] = connection;
}

35
@Override
public void run() {
try (Writer out = new BufferedWriter(new
OutputStreamWriter([Link]()))) {
[Link]("I am a multi-threaded server:\n");
Date now = new Date();
[Link]("Date and time: " + [Link]() + "\n");
[Link]();
} catch (IOException e) {
[Link]("Error with client " + [Link]() + ": " +
[Link]());
} finally {
try {
[Link]();
} catch (IOException e) {
[Link]("Error closing socket: " + [Link]());
}
}
}
}
}

36

You might also like