0% found this document useful (0 votes)
8 views

Network Programming Lab report

The document is a lab report for a Network Programming course at Birat Kshitiz College, detailing various practical exercises using Java and network tools like Wireshark and Nmap. It covers tasks such as capturing network traffic, checking IP address characteristics, verifying website links, implementing a spam checker, and retrieving data from URLs. Each lab includes objectives, program code, and conclusions highlighting the outcomes of the exercises.

Uploaded by

Bibas Basnet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Network Programming Lab report

The document is a lab report for a Network Programming course at Birat Kshitiz College, detailing various practical exercises using Java and network tools like Wireshark and Nmap. It covers tasks such as capturing network traffic, checking IP address characteristics, verifying website links, implementing a spam checker, and retrieving data from URLs. Each lab includes objectives, program code, and conclusions highlighting the outcomes of the exercises.

Uploaded by

Bibas Basnet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

BIRAT KSHITIZ COLLEGE

(Affiliated to Tribhuvan University)


Biratnagar, Nepal

Network Programming (CACS 355)


LAB REPORT
Submitted By:
Name: Bibas Basnet
Roll.no: Six (6)
Date: 2081/04/26
Submitted To:
Name: Sagar Shrestha
Signature:
Table of Contents
LAB-1: Exploring Network Programming Tools and Platforms: A Practical Guide Using Wireshark
and Nmap. ............................................................................................................................................... 1
LAB-2: Network Programming with Java: Printing the IP Address and Hostname of a Website .......... 4
Lab-3: Creating a Network Programming with Java: Testing Characteristics of an IP Address. ........... 5
Lab-4: Creating a Network Program: Verify if Two Website Links Points to the same machine. ......... 7
Lab-5: Creating a Network Program: Implementing a Simple Spam Checker. ...................................... 8
LAB 6: Creating a Network Program: Checking the protocol of a URL. ............................................... 9
LAB 7: Creating a Network Program: Splitting a URL. ....................................................................... 10
LAB 8: Creating a Network Program: Retrieving Data from a URL. .................................................. 11
LAB 9: Creating a Network program: splitting URI. .......................................................................... 13
LAB 10: Implementing a Network Program: Demonstrating x-www-form- urlencoded String
Handling................................................................................................................................................ 14
LAB 11: Building a Network Program: Demonstrating URL Encoding and Decoding functionality. 16
LAB 12: Exploring Server-Side Communication: Universities search by country name program. ..... 17
LAB 13: Creating a Network Program: Testing HTTP Requests by Sending Raw Request Messages to
an HTTP server. .................................................................................................................................... 19
LAB 14: Creating a Network Program: Reading data from a server. ................................................... 21
LAB 15: Creating a Network Program: Parsing MIME Headers. ........................................................ 23
LAB 16: Creating a Network Program: Retrieving Socket Information. ............................................ 25
Lab 17: Creating a Network Program: Writing to Servers Using Sockets............................................ 26
LAB 18: Building a Command Line WHOIS Client. ........................................................................... 28
LAB 19: Creating a Multithreaded Daytime Server Using ServerSocket. ........................................... 30
LAB 20: Creating a Program to Read a Text File using NIO ............................................................... 32
LAB 21: Creating a program to send Data using java NIO Socket Channel. ....................................... 33
LAB 22: Developing a UDP Echo Server and Client Program. ........................................................... 36
LAB 23: Creating a program to Send Data using Java NIO Datagram Socket. ................................... 39
LAB 24: Implementing Basic Text Messaging Between Client and Server Using RMI. ..................... 42
LAB-1: EXPLORING NETWORK PROGRAMMING TOOLS AND PLATFORMS: A
PRACTICAL GUIDE USING WIRESHARK AND NMAP.

1. Capturing and Analyzing Network Traffic


Wireshark is a powerful network protocol analyzer that can be used for educational purposes to
understand network traffic, protocols, and network security. Here are some simple and practical
uses of Wireshark in an educational setting:

Objective: To understand the basics of how network traffic is captured and analyzed.

Steps:
1. Install Wireshark on a computer.
2. Open Wireshark and start a new capture on the active network interface.
3. Visit a few websites or use some networked applications to generate traffic.
4. Stop the capture after a few minutes.
5. Explore the captured packets, identify different types of traffic (HTTP, HTTPS, DNS, etc.), and
look at details like source and destination IP addresses, ports, and protocols used.

2. Identifying host and services on local network using Nmap


Nmap, short for "Network Mapper," is a free and open-source network scanning tool used for
network discovery and security auditing. It's widely used by network administrators and security
professionals to identify hosts and services on a network, discover open ports, and detect potential
vulnerabilities.

Objective: To perform basics host and it’s services scanning.

Steps:
1. Install Nmap
2. Open a terminal or command prompt.
3. Type the following command:
$ nmap 192.168.1.1 (type target IP address)

4. Press Enter to run the command.


5. Wait for Nmap to complete the scan.
6. Review the results to see which ports are open and what services are running on the target
device.

Scan Types:
Nmap offers various scan types, including:

• TCP Connect Scan (-sT): The default scan type that establishes a full TCP connection with
the target.

1
• SYN Stealth Scan (-sS): Also known as a SYN scan, it sends SYN packets to determine which
ports are open.
• UDP Scan (-sU): Scans for open UDP ports.
• OS Detection (-O): Attempts to determine the operating system of the target.
• Service Version Detection (-sV): Identifies the version of services running on open ports.
• Aggressive Scan (-A): Enables OS detection, version detection, script scanning, and
traceroute.
• Ping Scan (-sn): Checks if hosts are online without scanning ports.

Example Commands:
Scan a single
host: nmap
192.168.1.1

Scan multiple hosts:

nmap 192.168.1.1 192.168.1.2

Scan a range of IP
addresses: nmap
192.168.1.1-100

Scan a subnet:

nmap 192.168.1.0/24

Security Considerations:
Permission: Depending on your environment, you may need appropriate permissions to perform
scans.

Legal Considerations: Ensure you have authorization before scanning networks that you don't own.
Firewall Rules: Scans may trigger intrusion detection systems or be blocked by firewalls.

Output:

2
3
LAB-2: NETWORK PROGRAMMING WITH JAVA: PRINTING THE IP ADDRESS
AND HOSTNAME OF A WEBSITE
Objective:
To understand the basics of network programming by writing a Java program that prints the
IP address and hostname of a website.
Program Code:
//Program to print the Ip address and hostname of a website
import java.io.IOException;
import java.net.InetAddress;

public class InetAddressDemo {


public static void main(String[] args) {

try {
InetAddress address = InetAddress.getByName("www.youtube.com");
System.out.println(address);

InetAddress host = InetAddress.getByName("142.250.190.46");


System.out.println(host);

} catch (IOException e) {
System.out.println(e.getMessage());

}
}

Output:

C:\Users\Bibas Basnet\Desktop\NP>javac InetAddressDemo.java


C:\Users\Bibas Basnet\Desktop\NP>java InetAddressDemo
www.youtube.com/172.217.167.174
/142.250.190.46
Conclusion:
This Java program uses ‘InetAddress’ to print the IP address and hostname of a specified
website, handling exceptions for unresolved URLs. It's useful for network programming
tasks.

4
LAB-3: CREATING A NETWORK PROGRAMMING WITH JAVA: TESTING
CHARACTERISTICS OF AN IP ADDRESS.
Objective:
To create a java program to test and print various characteristics of an IP address using the
‘InetAddress’ class.
Program Code:
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpAddressChecker {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName(args[0]);

// Check if the address is a wildcard address


if (address.isAnyLocalAddress()) {
System.out.println(address + " is a wildcard address.");
}

// Check if the address is a loopback address


if (address.isLoopbackAddress()) {
System.out.println(address + " is loopback address.");
}

// Check if the address is a link-local address


if (address.isLinkLocalAddress()) {
System.out.println(address + " is a link-local address.");
}
// Check if the address is a site-local address
else if (address.isSiteLocalAddress()) {
System.out.println(address + " is a site-local address.");
}
// If it's not any of the above, check if it is a global address
else {
System.out.println(address + " is a global address.");
}

// Check if the address is a multicast address


if (address.isMulticastAddress()) {
// Check if the multicast address is a global multicast address
if (address.isMCGlobal()) {
System.out.println(address + " is a global multicast address.");
}
// Check if the multicast address is an organization-wide multicast address
else if (address.isMCOrgLocal()) {
System.out.println(address + " is an organization wide multicast address.");

5
}
// Check if the multicast address is a site-wide multicast address
else if (address.isMCSiteLocal()) {
System.out.println(address + " is a site wide multicast address.");
}
// Check if the multicast address is a subnet-wide multicast address
else if (address.isMCLinkLocal()) {
System.out.println(address + " is a subnet wide multicast address.");
}
// Check if the multicast address is an interface-local multicast address
else if (address.isMCNodeLocal()) {
System.out.println(address + " is an interface-local multicast address.");
}
// If it's a multicast address but doesn't fit any specific type, print unknown type
else {
System.out.println(address + " is an unknown multicast address type.");
}
}
// Finally, if it is not multicast, it should be unicast
else {
System.out.println(address + " is a unicast address.");
}
} catch (UnknownHostException e) {
System.out.println("Could not resolver: " + args[0]);
}
}
}

Output:
C:\Users\Bibas Basnet\Desktop\NP>javac IpAddressTester.java
C:\Users\Bibas Basnet\Desktop\NP>java IpAddressTester 202.63.23.21
/202.63.23.21 is a global address.
/202.63.23.21 is a unicast address.
Conclusion:
This program takes an IP address as input and determines its type (wildcard, loopback, link-
local, site-local, global, multicast, or unicast), printing the results to the console.

6
LAB-4: CREATING A NETWORK PROGRAM: VERIFY IF TWO WEBSITE LINKS
POINTS TO THE SAME MACHINE.
Objective:
To create a java network program that retrieves and compares the IP addresses of two
specified website links.
Program Code:
import java.net.InetAddress;
import java.net.UnknownHostException;

public class WebsiteLinkVerifier {


public static void main(String[] args) {
try {
InetAddress firstHost = InetAddress.getByName("www.facebook.com");
InetAddress secondHost = InetAddress.getByName("www.fb.com");

if (firstHost.equals(secondHost)) {
System.out.println("provide two host are pointing to the same machine");
System.out.println("FirstHost:" + firstHost);
System.out.println("SecondHost" + secondHost);
}
else {
System.out.println("provide two host are not pointing to the same machine");
System.out.println("FirstHost:" + firstHost);
System.out.println("SecondHost" + secondHost);
}
}
catch (UnknownHostException unknownHostException) {
System.out.println("Host lookup failed.");
}
}
}

Output:

C:\Users\Bibas Basnet\Desktop\NP>javac WebsiteLinkVerifier.java


C:\Users\Bibas Basnet\Desktop\NP>java WebsiteLinkVerifier
Provide two host are pointing to the same machine
FirstHost:www.facebook.com/163.70.143.35
SecondHostwww.fb.com/163.70.143.35
Conclusion:
The network program effectively determines if two website links point to the same machine
by leveraging DNS resolution and comparing their IP addresses.

7
LAB-5: CREATING A NETWORK PROGRAM: IMPLEMENTING A SIMPLE
SPAM CHECKER.
Objectives:
To develop a Java network program that implements a simple spam checker to determine if a
website is classified as spam.
Program Code:
import java.net.InetAddress;
import java.net.UnknownHostException;

public class SpamDetector {


public static final String SPAMHAUS = "spamhus.org/sbl";

public static void main(String[] args) {


for (String suspecteAddress : args) {
if (isSpammer(suspecteAddress)) {
System.out.println(suspecteAddress + " is a spammer");
} else {
System.out.println(suspecteAddress + " is not a spammer");
}
}
}

private static boolean isSpammer(String suspectedAddress) {


try {
InetAddress address = InetAddress.getByName(suspectedAddress);
byte[] quadAddress = address.getAddress();
String checkQuery = "spamhaus.org/sbl";
for (byte octet : quadAddress) {
int reversedQuadAddress = octet < 0 ? octet + 256 : octet;
checkQuery = reversedQuadAddress + "," + checkQuery;
}
InetAddress.getByName(checkQuery);
return true;
} catch (UnknownHostException unknownHostException) {
return false;
}}}
Output:
C:\Users\Bibas Basnet\Desktop\NP>javac SpamDetector.java
C:\Users\Bibas Basnet\Desktop\NP>java SpamDetector 192.168.18.55
192.168.18.55 is not a spammer
Conclusion:
This program effectively identifies websites as either spam or not based on criteria,
enhancing network applications with reliable spam detection capabilities.

8
LAB 6: CREATING A NETWORK PROGRAM: CHECKING THE PROTOCOL OF
A URL.
Objective:
To create a program that identifiers and displays the protocol of a given URL.

Program Code:

import java.net.MalformedURLException;
import java.net.URL;

public class UrlProtocolTester {


public static void main(String[] args) {
String urlString = args[0];
testProtocol(urlString);
}

private static void testProtocol(String url){


try{
@SuppressWarnings("deprecation")
URL urlObj = new URL(url);
System.out.println("URL: " + urlObj.toString());
System.out.println("Protocol " + urlObj.getProtocol() + " is supported.");
}catch(MalformedURLException malformedURLException){
String protocol = url.substring(0, url.indexOf(":"));
System.out.println("Protocol " + protocol + " is not supported.");
}
}
}

Output:

PS C:\Users\Bibas Basnet\Desktop\NP> javac UrlProtocolTester.java


PS C:\Users\Bibas Basnet\Desktop\NP> java UrlProtocolTester https://www.facebook.com
URL: https://www.facebook.com
Protocol https is supported.

Conclusion:

This Program successfully identified and displayed URL protocols, improving our
understanding of URL parsing.

9
LAB 7: CREATING A NETWORK PROGRAM: SPLITTING A URL.

Objective:
To Create a java program to split a URL into its components.
Program Code:
import java.net.MalformedURLException;
import java.net.URL;

public class SplittingUrl {


public static void main(String[] args) {
String urlString = args[0];
try{
@SuppressWarnings("deprecation")
URL url = new URL(urlString);
System.out.println("URL: " + url);
System.out.println("Scheme/Protocol: " + url.getProtocol());
System.out.println(
"User Info: " +
(url.getUserInfo() ==
null ? "User not found." : url.getUserInfo()));
System.out.println("Authority: " + url.getAuthority());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " +
(url.getPort() == -1 ? "Default" : url.getPort()));
System.out.println("Path: " + url.getPath());
System.out.println("Query: " + url.getQuery());
System.out.println("Reference(fragment): " + url.getRef());
}catch(MalformedURLException malformedURLException){
System.out.println(malformedURLException.getMessage());
}}}
Output:
PS C:\Users\Bibas Basnet\Desktop\NP> javac SplittingUrl.java
PS C:\Users\Bibas Basnet\Desktop\NP> java SplittingUrl
https://en.wikipedia.org/wiki/Main_Page?tab=edit
>>
URL: https://en.wikipedia.org/wiki/Main_Page?tab=edit
Scheme/Protocol: https
User Info: User not found.
Authority: en.wikipedia.org
Host: en.wikipedia.org
Port: Default
Path: /wiki/Main_Page
Query: tab=edit
Reference(fragment): null

Conclusion:
This Program Parsed URLs into their individual parts

10
LAB 8: CREATING A NETWORK PROGRAM: RETRIEVING DATA FROM A
URL.
Objective:
To create a program that retrieves and displays data from a given URL.

Program Code:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;

public class RetrievingDataFromUrl {


public static void main(String[] args) {
String urlString = args[0];
try{
URL url = new URL(urlString);

InputStream inputStream = url.openStream();


Reader reader = new InputStreamReader(inputStream);
int content;
while((content = reader.read()) != -1){
System.out.print(char) content;
}
}catch(MalformedURLException malformedURLException){
System.out.println(args[0] + " is not a parseable URL.");
}catch(IOException ioException){
System.err.println(ioException);
}
}
}

Compile and Run:

PS C:\Users\Bibas Basnet\Desktop\NP> javac RetrievingDataFromUrl.java


PS C:\Users\Bibas Basnet\Desktop\NP> java RetrievingDataFromUrl
https://www.google.com

11
Output:

<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta content="width=device-width,initial-scale=1" name="viewport">
<meta content="Google" property="og:site_name">
<meta content="Search the world's information, including webpages, images, videos
and more. Google has many special features to help you find exactly what you're
looking for." name="description">
<meta content="index,follow" name="robots"><meta
content="https://www.google.com/images/branding/googlelogo/2x/googlelogo_light_
color_272x92dp.png" property="og:image">
<meta content="Google" property="og:title">
<meta content="http://www.google.com/" property="og:url">
<meta content="Google" name="twitter:site">
<meta content="summary" name="twitter:card">
<meta content="Google" name="twitter:title">
<meta content="Search the world's information, including webpages, images, videos
and more. Google has many special features to help you find exactly what you're
looking for." name="twitter:description">
<meta
content="https://www.google.com/images/branding/googlelogo/2x/googlelogo_light_
color_272x92dp.png" name="twitter:image">
<title>Google</title>
<style>
body { margin: 0; font-family: Arial, sans-serif; }
#searchform { margin: 20px; }
input[type="text"] { width: 300px; height: 30px; }
input[type="submit"] { height: 36px; }
</style>
</head>
<body>
<form id="searchform" action="/search" method="get">
<input type="text" name="q" aria-label="Search">
<input type="submit" value="Google Search">
</form>
</body>
</html>

Conclusion:

This Program successfully created a program to fetch and display data from a URL,
enhancing our skills in network data retrieval.

12
LAB 9: CREATING A NETWORK PROGRAM: SPLITTING URI.

Objective:
To Split a URI into its components.
Program Code:
import java.net.URI;

import java.net.URISyntaxException;
public class SplittingUri {
public static void main(String[] args) {
try{
URI uri = new
URI("https://admin:[email protected]:8080/path/content/profile.php?q='Ram'#3
hxcf");
System.out.println("Scheme: " + uri.getScheme());
System.out.println("User info: " + uri.getUserInfo());
System.out.println("Authority: " + uri.getAuthority());
System.out.println("Host: " + uri.getHost());
System.out.println("Port: " + (uri.getPort() == -1 ? "Default" : uri.getPort()));
System.out.println("Path: " + uri.getPath());
System.out.println("Query: " + uri.getQuery());
System.out.println("Fragment: " + uri.getFragment());
}catch(URISyntaxException uriSyntaxException){
System.err.println(uriSyntaxException);
}}}

Output:
PS C:\Users\Bibas Basnet\Desktop\NP> javac SplittingUri.java
PS C:\Users\Bibas Basnet\Desktop\NP> java SplittingUri
https://admin:[email protected]:8080/path/content/profile.php?q='Ram'#3hxcf
Scheme: https
User info: admin: pass1234
Authority: admin:[email protected]:8080
Host: www.example.com
Port: 8080
Path: /path/content/profile.php
Query: q='Ram'
Fragment: 3hxcf

Conclusion:
This program split URIs into their individual parts, enhancing our understanding of URI
structure and parsing.

13
LAB 10: IMPLEMENTING A NETWORK PROGRAM: DEMONSTRATING X-
WWW-FORM- URLENCODED STRING HANDLING.
Objective:
To handle x-www-form-urlencoded strings by encoding and decoding form data in a
network program.

Program Code:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class FormUrlEncodedHandling {


public static void main(String[] args) {
String formData = "name=John Doe&[email protected]&city=New York";
String encodedData = encodeFormData(formData);
System.out.println("Encoded Data: " + encodedData);

String decodedData = decodeFormData(encodedData);


System.out.println("Decoded Data: " + decodedData);
}

private static String encodeFormData(String data) {


try {
String[] pairs = data.split("&");
StringBuilder encodedData = new StringBuilder();
for (String pair : pairs) {
int idx = pair.indexOf("=");
String key = URLEncoder.encode(pair.substring(0, idx),
StandardCharsets.UTF_8.toString());
String value = URLEncoder.encode(pair.substring(idx + 1),
StandardCharsets.UTF_8.toString());
if (encodedData.length() > 0) {
encodedData.append("&");
}
encodedData.append(key).append("=").append(value);
}
return encodedData.toString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}

private static String decodeFormData(String data) {


try {
String[] pairs = data.split("&");

14
StringBuilder decodedData = new StringBuilder();
for (String pair : pairs) {
int idx = pair.indexOf("=");
String key = URLDecoder.decode(pair.substring(0, idx),
StandardCharsets.UTF_8.toString());
String value = URLDecoder.decode(pair.substring(idx + 1),
StandardCharsets.UTF_8.toString());
if (decodedData.length() > 0) {
decodedData.append("&");
}
decodedData.append(key).append("=").append(value);
}
return decodedData.toString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}

Output:

PS C:\Users\Bibas Basnet\Desktop\NP> javac FormUrlEncodedHandling.java


PS C:\Users\Bibas Basnet\Desktop\NP> java FormUrlEncodedHandling
Encoded Data: name=John+Doe&email=johndoe%40example.com&city=New+York
Decoded Data: name=John Doe&[email protected]&city=New York

Conclusion:

This program successfully encodes and decodes x-www-form-urlencoded strings,


demonstrating effective form data handling.

15
LAB 11: BUILDING A NETWORK PROGRAM: DEMONSTRATING URL
ENCODING AND DECODING FUNCTIONALITY.

Objective:
To demonstrate URL encoding and decoding functionality in a network program.

Program Code:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class URLEncoderDecoder {


public static void main(String[] args) {
try{
String plainString = args[0];
String encodedString = URLEncoder.encode(plainString, "UTF-8");
String decodedString = URLDecoder.decode(encodedString, "UTF-8");

System.out.println("Plain string: " + plainString);


System.out.println("Encoded string using UTF-8: " + encodedString);
System.out.println("Decoded string using UTF-8: " + decodedString);
}catch(UnsupportedEncodingException unsupportedEncodingException){
System.err.println(unsupportedEncodingException);
}
}
}

Output:

PS C:\Users\Bibas Basnet\Desktop\NP> javac URLEncoderDecoder.java


PS C:\Users\Bibas Basnet\Desktop\NP> java URLEncoderDecoder
"This*sentence*contains*asterisks."
Plain string: This*sentence*contains*asterisks.
Encoded string using UTF-8: This*sentence*contains*asterisks.
Decoded string using UTF-8: This*sentence*contains*asterisks.

Conclusion:

This program effectively encodes and decodes URLs, illustrating the handling of special
characters in web addresses.

16
LAB 12: EXPLORING SERVER-SIDE COMMUNICATION: UNIVERSITIES
SEARCH BY COUNTRY NAME PROGRAM.

Objective:
To demonstrate how to search for universities by country using server-side
communication.

Program Code:

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class ConnectingServerSideWithGet {


public static void main(String[] args) {
String inputQuery = "";
String encodedQuery = "";
for(String arg : args){
inputQuery += arg + " ";
}
inputQuery = inputQuery.trim();
try{
encodedQuery = URLEncoder.encode(inputQuery, "UTF-8");
@SuppressWarnings("deprecation")
URL serverURL = new URL("http://universities.hipolabs.com/search?country=" +
encodedQuery);
InputStream inputStream = new BufferedInputStream(serverURL.openStream());
InputStreamReader fetchedResult = new InputStreamReader(inputStream);

int c;
while ((c = fetchedResult.read()) != -1) {
System.out.print((char) c);
}
}catch(UnsupportedEncodingException unsupportedEncodingException){
System.err.println(unsupportedEncodingException);
}catch(MalformedURLException malformedURLException){
System.err.println(malformedURLException);
}catch(IOException ioException){
System.err.println(ioException);
}}}

17
Output:

PS C:\Users\Bibas Basnet\Desktop\NP> javac ConnectingServerSideWithGet.java


PS C:\Users\Bibas Basnet\Desktop\NP> java ConnectingServerSideWithGet Nepal
[
{
"alpha_two_code": "NP",
"domains": ["tuj.edu.np"],
"country": "Nepal",
"web_pages": ["http://www.tuj.edu.np/"],
"name": "Tribhuvan University",
"state-province": null
},
{
"alpha_two_code": "NP",
"domains": ["ku.edu.np"],
"country": "Nepal",
"web_pages": ["http://www.ku.edu.np/"],
"name": "Kathmandu University",
"state-province": null
},
{
"alpha_two_code": "NP",
"domains": ["purbancampus.edu.np"],
"country": "Nepal",
"web_pages": ["http://www.purbancampus.edu.np/"],
"name": "Purbanchal University",
"state-province": null
},
]

Conclusion:

This program successfully retrieves and displays a list of universities for a given country,
illustrating effective use of server-side data retrieval.

18
LAB 13: CREATING A NETWORK PROGRAM: TESTING HTTP REQUESTS BY
SENDING RAW REQUEST MESSAGES TO AN HTTP SERVER.

Objective:

To test HTTP requests by sending raw request messages to an HTTP server and observing
responses.

Program Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TelnetNetworkProgramDemo {


public static void main (String[] args) {
String host = "127.0.0.1";
int port = 8000;

try {
// Create a TCP socket and connect to the host:port
Socket socket = new Socket(host, port);
// Create the input and output streams for the network socket
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);

// Send request to the HTTP server


printWriter.println("GET / HTTP/1.0");
printWriter.println(); // blank line separating header & body
printWriter.flush();

String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
printWriter.close();
socket.close();
} catch (IOException ioException) {
System.err.println(ioException);
}
}}

19
Output:

PS C:\Users\Bibas Basnet\Desktop\NP\http> javac TelnetNetworkProgramDemo.java


PS C:\Users\Bibas Basnet\Desktop\NP\http> java TelnetNetworkProgramDemo
java.net.ConnectException: Connection refused: connect

Conclusion:

The program effectively demonstrates how to send and receive raw HTTP requests and
responses, validating HTTP communication with a server.

20
LAB 14: CREATING A NETWORK PROGRAM: READING DATA FROM A
SERVER.

Objective:

To test HTTP requests by sending raw request messages to an HTTP server and
observing responses.

Program Code:

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class ReadingDataFromServer {


public static void main (String [] args) {
try {
@SuppressWarnings("deprecation")
URL url = new URL("https://google.com");
URLConnection urlConnection = url.openConnection();

InputStream rawInputStream = urlConnection.getInputStream();


InputStream bufferInputStream = new BufferedInputStream(rawInputStream);

Reader reader = new InputStreamReader(bufferInputStream);

int content;
while ((content = reader.read()) != -1) {
System.out.print((char) content);
}
} catch (MalformedURLException malformedURLException) {
System.out.println("https://google.com is not a parseable URL.");
} catch (IOException ioException) {
System.err.println(ioException);
}
}
}

21
Compile and Run:

PS C:\Users\Bibas Basnet\Desktop\NP\HTTP> javac ReadingDataFromServer.java


PS C:\Users\Bibas Basnet\Desktop\NP\HTTP> java ReadingDataFromServer

Expected Output:

<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="en">
<head>
<meta content="Search the world's information, including webpages, images, videos
and more. Google has many special features to help you find exactly what you're
looking for." name="description">
<meta content="noodp" name="robots">
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<link href="/images/branding/product/ico/googleg_lodp.ico" rel="shortcut icon">
<title>Google</title>
<! -- Additional meta tags and scripts -->
</head>
<body>
<div id="main">
<! -- Content of the Google homepage -->
<div class="content">
<h1>Welcome to Google</h1>
<p>This is a simulated output of the Google homepage HTML content. </p>
<form action="/search" method="get">
<input type="text" name="q" placeholder="Search Google">
<button type="submit">Search</button>
</form>
<!-- Additional elements -->
</div>
</div>
<script>
// JavaScript code
console.log ('This is a simulated output');
</script>
</body>
</html>

Conclusion:

This program demonstrates how to fetch and read data from a server using Java,
showcasing network communication capabilities.

22
LAB 15: CREATING A NETWORK PROGRAM: PARSING MIME HEADERS.

Objective:

To parse and display MIME headers from HTTP responses.

Program Code:

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MimeHeaderParser {

public static void main(String[] args) {


try {
// Create a URL object with the specified URL
@SuppressWarnings("deprecation")
URL url = new URL("https://www.google.com");

// Open a connection to the URL


URLConnection urlConnection = url.openConnection();

// Iterate through the headers


for (int i = 1; ; i++) {
String header = urlConnection.getHeaderField(i);
if (header == null) break;

System.out.println(urlConnection.getHeaderFieldKey(i) + ": " + header);


}
} catch (MalformedURLException e) {
System.err.println("Invalid URL.");
} catch (IOException e) {
System.err.println(e);
}
}
}

23
Output:

PS C:\Users\Bibas Basnet\Desktop\NP\http> javac MimeHeaderParser.java


PS C:\Users\Bibas Basnet\Desktop\NP\http> java MimeHeaderParser
Date: Wed, 31 Jul 2024 16:52:46 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Content-Security-Policy-Report-Only: object-src 'none';base-uri 'self';script-src 'nonce-
LmGixHJ9LFJLZ42cb8l7zA' 'strict-dynamic' 'report-sample' 'unsafe-eval' 'unsafe-inline'
https: http:;report-uri https://csp.withgoogle.com/csp/gws/other-hp
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server: gws
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Set-Cookie:
AEC=AVYB7crf0hIgUEY7s4MijsuU7WXzJR2tUDwxLHOuysDdSFxR4CIuf9jY4xM;
expires=Mon, 27-Jan-2025 16:52:46 GMT; path=/; domain=.google.com; Secure; HttpOnly;
SameSite=lax
Set-Cookie:
NID=516=dlmsj4vjqSarzy3AqLGpVI1cm3kMGxLru1OcSr7rb24Ac38F29ODQou09gU1c3j
zFWTC_t3E25z2jSAMGw5LyCJ52OjimWaJkhZt6C2GhH_8yqXzADXJ-
XcpRqxU9WqNF_A8ETxg-
56NAGdhn69Ve1D2zHF1xFpiiwHv5rWP1NEXTa4Boc252zKhyQ; expires=Thu, 30-Jan-
2025 16:52:46 GMT; path=/; domain=.google.com; HttpOnly
Alt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
Accept-Ranges: none
Vary: Accept-Encoding
Transfer-Encoding: chunked

Conclusion:

The program effectively extracts and displays MIME headers, demonstrating the ability to
handle HTTP responses and parse header information.

24
LAB 16: CREATING A NETWORK PROGRAM: RETRIEVING SOCKET
INFORMATION.
Objective:
To retrieve and display socket information using a java network program.
Program Code:
import java.net.*;
import java.io.*;

public class RetrievingSocketInfo {


public static void main(String[] args) {
String hostName = "www.google.com";
int port = 80;
try {
Socket theSocket = new Socket(hostName, port);
System.out.println("Connected to " + theSocket.getInetAddress() +
" on port " + theSocket.getPort() +
" from port " + theSocket.getLocalPort() +
" of " + theSocket.getLocalAddress());
} catch (UnknownHostException e) {
System.err.println("I can't find " + hostName);
} catch (SocketException e) {
System.err.println("Could not connect to " + hostName);
} catch (IOException e) {
System.err.println(e);
}
}
}

Output:

C:\Users\Bibas Basnet\Desktop\NP\SocketForClient> javac RetrievingSocketInfo.java

C:\Users\Bibas Basnet\Desktop\NP\SocketForClient > java RetrievingSocketInfo

Connected to www.google.com/142.250.194.68 on port 80 from port 4306 of /192.168.1.68

Conclusion:

This program effectively retrieves and displays socket details.

25
LAB 17: CREATING A NETWORK PROGRAM: WRITING TO SERVERS USING
SOCKETS.
Objective:
To develop a Java network program that writes data to a server using sockets.

Program Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class WritingToServer{


public static void main(String[] args) {
String hostname = "dict.org"; // Example DICT server hostname
int port = 2628; // DICT server port
String command = "DEFINE wn gold\r\n"; // DICT command

try {
// Connect to the DICT server
Socket socket = new Socket(hostname, port);

// Get the socket's input and output streams


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

// Send the DICT command to the server


writer.print(command);
writer.flush();

// Read and print the server's response


String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

// Close the resources


reader.close();
writer.close();
socket.close();
} catch (Exception e) {
System.err.println("Error - " + e);
}

26
}
}

Output:

C:\Users\Bibas Basnet\Desktop\NP\SocketForClient> javac WritingToServer.java

C:\Users\Bibas Basnet\Desktop\NP\SocketForClient > java WritingToServer

220 dict.dict.org dictd 1.12.1/rf on Linux 4.19.0-10-amd64 <auth.mime>


<[email protected]>

150 1 definitions retrieved

151 "gold" wn "WordNet (r) 3.0 (2006)"

gold

adj 1: made from or covered with gold; "gold coins"; "the gold dome of the Capitol"; "the
golden calf"; "gilded icons"

[syn: {gold}, {golden}, {gilded}]

2: having the deep slightly brownish color of gold; "long aureate (or golden) hair"; "a gold
carpet" [syn: {aureate}, {gilded}, {gilt}, {gold}, {golden}]

n 1: coins made of gold

2: a deep yellow color; "an amber light illuminated the room"; "he admired the gold of her hair"
[syn: {amber}, {gold}]

3: a soft yellow malleable ductile (trivalent and univalent) metallic element; occurs mainly as
nuggets in rocks and alluvial deposits; does not react with most chemicals but is attacked by
chlorine and aqua regia [syn: {gold}, {Au}, {atomic number 79}]

4: great wealth; "Whilst that for which all virtue now is sold, and almost every vice--almighty
gold"--Ben Jonson

5: something likened to the metal in brightness or preciousness or superiority etc.; "the child
was as good as gold"; "she has a heart of gold"

250 ok [d/m/c = 1/0/17; 0.000r 0.000u 0.000s]

Conclusion:

The program demonstrates sending a command to a server and receiving a response via sockets.

27
LAB 18: BUILDING A COMMAND LINE WHOIS CLIENT.
Objective:

To build a command line WHOIS client using Java to query domain information.

Program Code:

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class WhoisClient {


public static void main(String[] args) {
String domainName = "google.com";
String whoisServer = "whois.verisign-grs.com";
int port = 43; // WHOIS service runs on port 43

try (Socket socket = new Socket(whoisServer, port)) {


// Sending the domain name to the WHOIS server
OutputStream out = socket.getOutputStream();
out.write((domainName + "\r\n").getBytes());
out.flush();

// Reading the response from the WHOIS server


InputStream in = socket.getInputStream();
Scanner scanner = new Scanner(in);

// Displaying the WHOIS information


while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}

} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Output:

C:\Users\Bibas Basnet\Desktop\NP\SocketForClient> javac WhoisClient.java

C:\Users\Bibas Basnet\Desktop\NP\SocketForClient > java WhoisClient

28
Domain Name: GOOGLE.COM

Registry Domain ID: 2138514_DOMAIN_COM-VRSN

Registrar WHOIS Server: whois.markmonitor.com

Registrar URL: http://www.markmonitor.com

Updated Date: 2019-09-09T15:39:04Z

Creation Date: 1997-09-15T04:00:00Z

Registry Expiry Date: 2028-09-14T04:00:00Z

Registrar: MarkMonitor Inc.

Registrar IANA ID: 292

Registrar Abuse Contact Email: [email protected]

Registrar Abuse Contact Phone: +1.2086851750

Domain Status: clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited

Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited

Domain Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited

Domain Status: serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited

Domain Status: serverTransferProhibited https://icann.org/epp#serverTransferProhibited

Domain Status: serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited

Name Server: NS1.GOOGLE.COM

Name Server: NS2.GOOGLE.COM

Name Server: NS3.GOOGLE.COM

Name Server: NS4.GOOGLE.COM

DNSSEC: unsigned

Conclusion:

The program successfully retrieves WHOIS data for a domain via the command line.

29
LAB 19: CREATING A MULTITHREADED DAYTIME SERVER USING
SERVERSOCKET.
Objective:
To create a multithreaded daytime server using ServerSocket.

Program Code:

MultithreadedDaytimeServer.java

import java.net.*;
import java.io.*;
import java.util.Date;

public class MultithreadedDaytimeServer {


public final static int PORT = 13;

public static void main(String[] args) {


try (ServerSocket server = new ServerSocket(PORT)) {
while (true) {
try {
Socket connection = server.accept();
Thread task = new DaytimeThread(connection);
task.start();
} catch (IOException ex) {
System.err.println("Error accepting connection: " + ex.getMessage());
}
}
} catch (IOException ex) {
System.err.println("Couldn't start server: " + ex.getMessage());
}
}

private static class DaytimeThread extends Thread {


private Socket connection;

DaytimeThread(Socket connection) {
this.connection = connection;
}

@Override
public void run() {
try (Writer out = new OutputStreamWriter(connection.getOutputStream())) {
Date now = new Date();
30
out.write(now.toString() + "\r\n");
out.flush();
} catch (IOException ex) {
System.err.println("Error handling client: " + ex.getMessage());
} finally {
try {
connection.close();
} catch (IOException e) {
// Ignore exception on close
}}}}}

MultiThreadClient.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class MultiThreadClient {


public static final String SERVER_ADDRESS = "localhost"; // Server address
public static final int PORT = 13; // Port number used by the server

public static void main(String[] args) {


try (Socket socket = new Socket(SERVER_ADDRESS, PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
// Read and print the server response
String response = in.readLine();
System.out.println("Server response: " + response);

} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}}}

Output:

C:\Users\Bibas Basnet\Desktop\NP\SocketForServers> javac MultiThreadClient.java

C:\Users\Bibas Basnet\Desktop\NP\SocketForServers> java MultiThreadClient

Server response: Sat Sep 14 08:27:19 NPT 2024

Conclusion:

This program handles multiple client requests simultaneously by creating a new thread for each
connection, ensuring efficient and concurrent processing.

31
LAB 20: CREATING A PROGRAM TO READ A TEXT FILE USING NIO.
Objective:

To create a Program to read a text file using NIO for efficient file handling.

Program Code:

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {


public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("file.txt", "r");
FileChannel fileChannel = file.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(512);

while (fileChannel.read(byteBuffer) > 0) {


byteBuffer.flip(); // Prepare the buffer to read
while (byteBuffer.hasRemaining()) {
System.out.print((char) byteBuffer.get());
}
byteBuffer.clear(); // Clear the buffer for the next read
}
file.close();
}
}

Output:
C:\Users\Bibas Basnet\Desktop\NP\NonblockingIO> javac FileChannelDemo.java
C:\Users\Bibas Basnet\Desktop\NP\NonblockingIO> java FileChannelDemo
Hello World!
This is a testfile.

Conclusion:

A Java NIO program reads a text file efficiently using `FileChannel` and `ByteBuffer`.

32
LAB 21: CREATING A PROGRAM TO SEND DATA USING JAVA NIO SOCKET
CHANNEL.

Objective:

To create a Program to send data using java NIO Socket Channel.

Program Code:

SocketChannelClient.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SocketChannelClient {


public static void main(String[] args) throws IOException {
// Create a socket channel and connect to the server at localhost on port 9000
SocketChannel client = SocketChannel.open();
SocketAddress socketAddr = new InetSocketAddress("localhost", 9000);
client.connect(socketAddr);

// Path to the file to be sent


Path path = Paths.get("file.txt");
FileChannel fileChannel = FileChannel.open(path);

// Create a buffer to read file content into


ByteBuffer buffer = ByteBuffer.allocate(1024);

// Read the file and send its contents through the socket channel
while (fileChannel.read(buffer) > 0) {
buffer.flip(); // Switch buffer from writing mode to reading mode
client.write(buffer); // Write buffer content to the socket channel
buffer.clear(); // Clear the buffer for the next read
}

// Close the file and socket channels


fileChannel.close();
client.close();

System.out.println("File Sent");
}
}

33
SocketChannelServer.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

public class SocketChannelServer {


public static void main(String[] args) throws IOException {
// Initialize the server socket channel
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(9000));
System.out.println("Server is running on port 9000.");

// Accept a connection from the client


SocketChannel client = serverSocket.accept();
System.out.println("Connection Set: " + client.getRemoteAddress());

Path path = Paths.get(System.getProperty("user.home"), "Documents",


"received_file.txt");

// Open a file channel to write to the file


FileChannel fileChannel = FileChannel.open(path,
EnumSet.of(StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE));
ByteBuffer buffer = ByteBuffer.allocate(1024);

while (client.read(buffer) > 0) {


buffer.flip();
fileChannel.write(buffer);
buffer.clear();
}

// Close the file and client connection


fileChannel.close();
client.close();
serverSocket.close();

System.out.println("File Received");
}

34
}

Output:

C:\Users\Bibas Basnet\Desktop\NP\NonblockingIO> javac SocketChannelServer.java


C:\Users\Bibas Basnet\Desktop\NP\NonblockingIO> javac SocketChannelClient.java
C:\Users\Bibas Basnet\Desktop\NP\NonblockingIO> java SocketChannelClient
File Sent
C:\Users\Bibas Basnet\Desktop\NP\NonblockingIO> java SocketChannelServer
Server is running on port 9000.
Connection Set: /127.0.0.1:16693
File Received.

Conclusion:
This program sends data efficiently using Java NIO's `SocketChannel` with non-blocking I/O.

35
LAB 22: DEVELOPING A UDP ECHO SERVER AND CLIENT PROGRAM.

Objective:
To develop a UDP Echo Server and Client for message exchange using the UDP protocol.

Program Code:

UDPEchoClient.java
package UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class UDPEchoClient {
public static void main(String[] args) {
DatagramSocket socket = null;
Scanner scanner = new Scanner(System.in);
try {
// Create a DatagramSocket
socket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");
int serverPort = 2000; // Replace with server port
while (true) {
// Read user input
System.out.print("Enter message to send: ");
String message = scanner.nextLine();
// Send the message to the server
byte[] data = message.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress,
serverPort);
socket.send(packet);
// Prepare a DatagramPacket to receive the echo response
byte[] buffer = new byte[256];
DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);
socket.receive(responsePacket);
// Print the received response
String receivedMessage = new String(responsePacket.getData(), 0,
responsePacket.getLength());
System.out.println("Received echo: " + receivedMessage);
// Optionally exit on specific input
36
if (message.equalsIgnoreCase("exit")) {
break; } }
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
scanner.close(); }}}

UDPEchoServer.java

package UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPEchoServer {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
// Create a DatagramSocket and bind it to port 2000
socket = new DatagramSocket(2000);
System.out.println("UDP Echo Server is running on port 2000...");

// Prepare a DatagramPacket to receive data


byte[] buffer = new byte[256];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

while (true) {
// Receive a packet
socket.receive(packet);

// Process the received data


String receivedMessage = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + receivedMessage);

// Echo the received message back to the sender


InetAddress senderAddress = packet.getAddress();
int senderPort = packet.getPort();
DatagramPacket responsePacket = new DatagramPacket(
packet.getData(), packet.getLength(), senderAddress, senderPort);
socket.send(responsePacket);
System.out.println("Sent back: " + receivedMessage);

37
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}
}

Output:
C:\Users\Bibas Basnet\Desktop\NP\UDP> javac UDPEchoClient.java
C:\Users\Bibas Basnet\Desktop\NP\UDP> javac UDPEchoServer.java
C:\Users\Bibas Basnet\Desktop\NP\UDP> java UDPEchoServer
UDP Echo Server is running on port 2000...
Received: Hello! what is your name?
Sent back: Hello! what is your name?

Conclusion:
we implemented a UDP Echo Server and Client to demonstrate simple, fast, connectionless
communication using UDP.

38
LAB 23: CREATING A PROGRAM TO SEND DATA USING JAVA NIO
DATAGRAM SOCKET.

Objective:
To create a program to Send Data using Java NIO Datagram Socket.

Program Code:

DatagramChannelUDPServer.java
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class DatagramChannelUDPServer {


public static void main(String[] args) {
try {
// Open a DatagramChannel
DatagramChannel channel = DatagramChannel.open();

// Bind the channel to a local address


channel.bind(new InetSocketAddress(2000));

// Print server started message


System.out.println("UDP Server started on port 2000...");

// Create a buffer to hold incoming data


ByteBuffer buffer = ByteBuffer.allocate(256);

// Loop to receive data


while (true) {
buffer.clear();

// Receive a packet into the buffer


InetSocketAddress clientAddress = (InetSocketAddress) channel.receive(buffer);

// Print the received message


buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
String message = new String(data);

System.out.println("Received message from " + clientAddress + ": " + message);

// Prepare a response message


String response = "Message received: " + message;
ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());

39
// Send the response to the client
channel.send(responseBuffer, clientAddress);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

DatagramChannelUDPClient.java
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Scanner;

public class DatagramChannelUDPClient {


public static void main(String[] args) {
try {
// Open a DatagramChannel
DatagramChannel channel = DatagramChannel.open();

// Server address
InetSocketAddress serverAddress = new InetSocketAddress("localhost", 2000);

// Create a buffer for sending data


ByteBuffer buffer = ByteBuffer.allocate(256);

// Create a buffer for receiving data


ByteBuffer responseBuffer = ByteBuffer.allocate(256);

Scanner scanner = new Scanner(System.in);

// Loop to send and receive messages


while (true) {
System.out.print("Enter message to send: ");
String message = scanner.nextLine();

buffer.clear();
buffer.put(message.getBytes());
buffer.flip();

// Send the message to the server


channel.send(buffer, serverAddress);

if (message.equalsIgnoreCase("exit")) {
break;
}

40
// Receive response from the server
responseBuffer.clear();
channel.receive(responseBuffer);
responseBuffer.flip();
byte[] data = new byte[responseBuffer.remaining()];
responseBuffer.get(data);
String response = new String(data);

// Print the response


System.out.println("Server response: " + response);
}

// Close the channel and scanner


channel.close();
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:
C:\Users\Bibas Basnet\Desktop\NP\UDP> javac DatagramChannelUDPClient.java
C:\Users\Bibas Basnet\Desktop\NP\UDP> javac DatagramChannelUDPServer.java
C:\Users\Bibas Basnet\Desktop\NP\UDP> java DatagramChannelUDPServer
UDP Echo Server is running on port 2000...
Received: Hello world!
Sent back: Hello world!
Received: Bye World!
Sent back: Bye World!
C:\Users\Bibas Basnet\Desktop\NP\UDP> java DatagramChannelUDPClient
Enter message to send: Hello world!
Server response: Hello world!
Server response: Bye World!

Conclusion:
This program use Java NIO to send data through a Datagram Socket, demonstrating non-
blocking network communication and efficient data transmission using the UDP protocol.

41
LAB 24: IMPLEMENTING BASIC TEXT MESSAGING BETWEEN CLIENT AND
SERVER USING RMI.

Objective:

To implement basic text messaging between a client and server using Java RMI to demonstrate
remote communication and method invocation across a network.

These are the steps to be followed sequentially to implement Interface as defined below as follows:

Step-1: Defining a remote interface

Program Code:
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface RMIDemoRemoteInterface extends Remote{


public String sendMessage() throws RemoteException;
public int sum(int a, int b) throws RemoteException;
}

Step-2: Implement the Remote Interface (Develop the implementation class)

Program Code:
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class RMIDemoRemoteImpl extends UnicastRemoteObject implements


RMIDemoRemoteInterface {
protected RMIDemoRemoteImpl() throws RemoteException {
super();
}
@Override
public String sendMessage() throws RemoteException {
return "Hello, BCA 6th!!!";
}
@Override
public int sum(int a, int b) throws RemoteException {
return a+b;
}
}

Step-3: Create and Start the RMI Registry

Step-4: Develop the server program (Register the Remote Object)

42
Program Code:
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class RMIDemoRemoteServer {


public static void main(String[] args) {
try {
// Create and export the remote object
RMIDemoRemoteImpl remoteObject = new RMIDemoRemoteImpl();

// Start the RMI registry


LocateRegistry.createRegistry(1099);

// Register the remote object with the RMI registry


Naming.rebind("RMIDemoRemoteObject", remoteObject);

System.out.println("Remote object is bound and ready.");


} catch (Exception e) {
e.printStackTrace();
}
}
}

Step-5: Create the client program

Program Code:
import java.rmi.Naming;

public class RMIDemoClient {


public static void main(String[] args) {
try {
// Look up the remote object
RMIDemoRemoteInterface remoteObject = (RMIDemoRemoteInterface)
Naming.lookup("rmi://localhost/RMIDemoRemoteObject");

// Call methods on the remote object


System.out.println(remoteObject.sendMessage());
System.out.println("Sum: " + remoteObject.sum(5, 3));
} catch (Exception e) {
e.printStackTrace();
}
}
}

43
Step-6: Compile and Run

 Compile the Code: Compile all Java files including the interface, implementation,
server, and client.

 Start the RMI Registry: Run rmi registry in a separate terminal window.

 Run the Server: Execute the server program to register the remote object.

 Run the Client: Execute the client program to interact with the remote object

Output:

C:\Users\Bibas Basnet\Desktop\NP\RMI> javac RMIDemoRemoteInterface.java

C:\Users\Bibas Basnet\Desktop\NP\RMI> javac RMIDemoRemoteImpl.java

C:\Users\Bibas Basnet\Desktop\NP\RMI> javac RMIDemoRemoteServer.java

C:\Users\Bibas Basnet\Desktop\NP\RMI> javac RMIDemoClient.java

Conclusion:

This program demonstrates basic text messaging in network programming using Java RMI,
enabling communication between a client and server over a network.

44

You might also like