Name: Nithin Joel J Course Name: Distributed Systems
Reg No: 22MID0140 Course Code: CSi3012
LAB-ASSIGNMENT-1
1. Write a Java program to parse a given URL and display its protocol, host
name, port number, file name, and query string.
Code:
import [Link];
import [Link];
public class URLParser {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a URL: ");
String urlString = [Link]();
try {
URL url = new URL(urlString);
[Link]("Protocol : " +
[Link]());
[Link]("Host : " +
[Link]());
[Link]("Port : " +
([Link]() == -1 ? "Default" : [Link]()));
[Link]("File : " +
[Link]());
[Link]("Query : " +
[Link]());
} catch (Exception e) {
[Link]("Invalid URL!");
}
}
}
Output:
2. Write a Java program to connect to a web server and display the HTTP
status code returned.
import [Link];
import [Link];
import [Link];
public class HTTPStatus {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter website URL: ");
String site = [Link]();
try {
URL url = new URL(site);
HttpURLConnection con = (HttpURLConnection)
[Link]();
[Link]("GET");
int status = [Link]();
[Link]("HTTP Status Code: " +
status);
[Link]("Response Message: " +
[Link]());
} catch (Exception e) {
[Link]("Error connecting to
server!");
}
}
}
Output:
3. Write a Java program to implement a concurrent echo server that can handle
multiple clients simultaneously using threads. The server should receive
messages from each client and echo the same message back to the respective
client.
Code Server:
import [Link].*;
import [Link].*;
class ClientHandler extends Thread {
private Socket client;
public ClientHandler(Socket socket) {
[Link] = socket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(
new
InputStreamReader([Link]()));
PrintWriter out = new
PrintWriter([Link](), true);
String msg;
while ((msg = [Link]()) != null) {
[Link]("Client: " + msg);
[Link]("Echo: " + msg);
}
[Link]();
} catch (Exception e) {
[Link]("Client disconnected.");
}
}
}
public class EchoServer {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8080);
[Link]("Echo Server started on
port 8080");
while (true) {
Socket client = [Link]();
[Link]("Client connected: " +
[Link]());
new ClientHandler(client).start();
}
} catch (Exception e) {
[Link]("Server error!");
}
}
}
Code Client:
import [Link].*;
import [Link].*;
import [Link];
public class EchoClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8080);
BufferedReader in = new BufferedReader(
new
InputStreamReader([Link]()));
PrintWriter out = new
PrintWriter([Link](), true);
Scanner sc = new Scanner([Link]);
[Link]("Type messages (type 'exit'
to quit):");
String msg;
while (!(msg =
[Link]()).equalsIgnoreCase("exit")) {
[Link](msg);
[Link]([Link]());
}
[Link]();
} catch (Exception e) {
[Link]("Client error!");
}
}
}
Output:
Server
Client