0% found this document useful (0 votes)
13 views8 pages

Java Networking Examples and Code

This document contains code for 4 Java programs using network programming concepts: 1. A program to parse parts of a URL like protocol, file, port, and path. 2. A program to download the contents of a web page using URL and URLConnection classes. 3. A client-server program where the client requests a file's last modification time from the server. 4. A mini chat application with client and server that can initiate a "STOP" request to end chatting.
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)
13 views8 pages

Java Networking Examples and Code

This document contains code for 4 Java programs using network programming concepts: 1. A program to parse parts of a URL like protocol, file, port, and path. 2. A program to download the contents of a web page using URL and URLConnection classes. 3. A client-server program where the client requests a file's last modification time from the server. 4. A mini chat application with client and server that can initiate a "STOP" request to end chatting.
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

Name = Anamika Shrivastav

Roll No = 543

Division = B

[Link] to get the parts of an URL with the help of [Link](), [Link](), [Link](),
[Link]() methods etc. of [Link] class.

CODE :

import [Link];

public class URLinParts{


public static void main(String args[]) throws Exception{
String urlStr = "[Link]
URL url = new URL(urlStr);
[Link]("URL is " + [Link]());
[Link]("Protocol is " + [Link]());
[Link]("File name is " + [Link]());
[Link]("Host is " + [Link]());
[Link]("Path is " + [Link]());
[Link]("Port is " + [Link]());
[Link]("Default port is " + [Link]());

}
}

OUTPUT :
[Link] the contents of a Web page, Use URL & URLConnection classes ?

CODE :

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

public class DownloadWebPage {


public static void main(String[] args) {
URL url;
String urlStr =
"[Link]
%20Networking/Soctket%20Programming/[Link]";
String line;

try {
url = new URL(urlStr);
InputStream inputStream = [Link]();
BufferedReader bReader = new BufferedReader(new
InputStreamReader(inputStream));

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


[Link](line);
}
} catch (IOException ioe) {
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

OUTPUT :

[Link] a Java Program where the client will send the file request to the server and the server will
respond when was that file last modified in the following Date Format : "dd MM yyyy HH:mm:ss:SSS Z" ?

CODE :

Client

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

public class CliReqLastModi {


public static void main(String args[]) throws IOException {

Socket socket = new Socket([Link](), 5217);


[Link]("Request sent ... ");

// read file name


BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter tht filename : ");
String fileString = [Link]();

// outputstream
DataOutputStream dataOutputStream = new
DataOutputStream([Link]());
[Link](fileString);

DataInputStream dataInputStream = new


DataInputStream([Link]());
String msg = [Link]();
[Link](msg);
}

Server

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

public class SerResLastModi {


public static void main(String args[]) throws IOException{

ServerSocket serverSocket = new ServerSocket(5217);

[Link]("Server is running and waiting for client request ");


Socket socket = [Link]();

//reading from keyboard


DataInputStream dataInputStream = new
DataInputStream([Link]());
String fileString = [Link]();

DataOutputStream dataOutputStream = new


DataOutputStream([Link]());
URL url = new URL(fileString);
URLConnection urlConnection = [Link]();

//timestamp
long timestamp = [Link]();
SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy HH:mm:ss:SSS Z");
Date dt = new Date(timestamp);
[Link]("The last modification time is :"
+[Link](dt));

}
}

OUTPUT :

[Link] a mini chatting application which includes Java Socket program that runs on a server which
accepts a message from client & server gives the response, either the client or the server can initiate the
"STOP" request to stop chaatting?

CODE :

Server

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

public class ChatServer {


public static void main(String args[]) throws Exception {
ServerSocket serverSocket = new ServerSocket(3000);
[Link]("server is running and waiting for client to start ...
");
Socket socket = [Link]();
[Link]("Connection established ... ");
[Link]("Start chatting ... ");
[Link]("Type 'STOP' to chatting");

BufferedReader keyboardBufferedReader = new BufferedReader(new


InputStreamReader([Link]));
PrintWriter printWriter = new PrintWriter([Link](),
true);
BufferedReader rBufferedReader = new BufferedReader(new
InputStreamReader([Link]()));

try {
String receiveMessage = "";
String sendMessage = "";

while (![Link]("STOP")) {
sendMessage = [Link](); // read keyboard
[Link](sendMessage);// sending to server
[Link]();
if ((receiveMessage = [Link]()) != null) {
[Link](receiveMessage);
} else if ((receiveMessage = [Link]()) !=
"STOP") {
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}

}
} catch (Exception e) {
[Link]("Chatting stopped ... ");
}

}
}

Client

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

public class ChatClient {


public static void main(String args[]) throws Exception {
Socket socket = new Socket([Link](), 3000);

BufferedReader keyboardBufferedReader = new BufferedReader(new


InputStreamReader([Link]));
PrintWriter printWriter = new PrintWriter([Link](),
true);
BufferedReader rBufferedReader = new BufferedReader(new
InputStreamReader([Link]()));

[Link]("Start chatting ... ");


[Link]("Type 'STOP' to stop chatting");

try {
String receivedMessage = "", sendMessage = "";
while (![Link]("STOP")) {
sendMessage = [Link](); // read keyboard
[Link](sendMessage);// sending to server
[Link]();

if ((receivedMessage = [Link]()) != null) {


[Link](receivedMessage);
} else if ((receivedMessage = [Link]()) !=
"STOP") {
[Link]();
[Link]();
[Link]();
[Link]();
}
}
} catch (Exception e) {
[Link]("Chatting Stopped ... ");
}

}
}

OUTPUT :

Common questions

Powered by AI

Java's `URL` and `URLConnection` classes facilitate the downloading of web content by first creating a `URL` object pointing to the desired resource and then opening a connection with `url.openConnection()`. This `URLConnection` object allows for retrieving an `InputStream` with `urlConnection.getInputStream()` to read web content. `BufferedReader` can be utilized to read this stream line-by-line. Careful handling of exceptions like `MalformedURLException` and `IOException` is necessary, as is ensuring the `BufferedReader` and InputStream are closed after use to prevent resource leaks .

To handle errors more gracefully in the file modification time retrieval application, exceptions should be specifically caught and handled to provide informative messages to the user. For instance, `FileNotFoundException` or `IOException` should log specific errors about file access or connectivity issues. Additionally, resources like sockets and streams should be closed in a finally block or using try-with-resources to ensure proper resource management. Adding checks to verify that files and URLs exist could prevent unnecessary network calls and handle cases where files might not be accessible or do not exist .

In the Java Socket-based chatting application, the connection setup starts with the server invoking `ServerSocket.accept()`, which listens for incoming client connections. The client initiates a connection by creating a `Socket` with the server’s IP address and the port number where the `ServerSocket` is listening. Upon successful connection establishment, the server prints 'Connection established ... ' and both client and server create input and output streams to start message exchange. The sequence ensures that both parties are ready to send and receive messages upon establishing the connection .

Implementing a client-server application for fetching a file's last modified date requires handling networking communication effectively. The client needs to send a request containing the file name to the server, which listens on a specific port. The server needs to parse the request using the `DataInputStream` and obtain the last modified timestamp using `URLConnection.getLastModified()`, converting it to a formatted date using `SimpleDateFormat`. Error handling for IOExceptions and ensuring the server properly closes connections after use to prevent resource leaks is also crucial .

The mini chatting application uses the keyword 'STOP' as a trigger to end the communication between the client and server. Both the client and server check for this keyword in the messages they receive, using loops that continue processing until 'STOP' is detected in the received message. Once 'STOP' is detected, the application breaks out of the loop and proceeds to close resources such as sockets, input streams, and output streams, thereby terminating the chat session .

Handling a 'STOP' request in Java socket programming is significant as it allows for a controlled termination of the communication session. It ensures both the client and server can independently initiate an end to the session, contributing to flexibility and user control. This mechanism prevents abrupt disconnections that can lead to resource leaks or incomplete communications, which are critical in maintaining the stability and robustness of networked applications. By detecting 'STOP', applications can properly close sockets and free associated resources, mitigating potential memory leaks .

The `java.net.URL` class provides several methods to access different components of a URL. `url.getProtocol()` returns the protocol of the URL, `url.getFile()` gives the file name of the URL path, `url.getHost()` retrieves the host name, `url.getPath()` gets the path component of the URL, `url.getPort()` returns the port number, and `url.getDefaultPort()` returns the default port number for the protocol. This functionality allows for the parsing and utilization of URLs effectively within Java applications .

Enhancing the user experience in a socket-based mini chatting application could involve implementing a graphical user interface (GUI) using JavaFX or Swing to provide a more intuitive and visually appealing environment than console interaction. Features such as message timestamps, typing indicators, and notification sounds can simulate real-time communication responsiveness. Additionally, implementing error handling to inform users of connectivity issues, along with options to automatically reconnect, would improve reliability. Integrating encryption could secure data transmission, promoting user trust in privacy and security .

A potential use case for a client-server application that retrieves a file's last modification time is in a distributed system where data consistency is crucial. For example, in a content management system (CMS), clients may request the last modification times of files to determine if they have the latest versions before performing updates or modifications. This ensures that cache systems or local copies are synchronized with the server's data, maintaining version control and reducing unnecessary data transfer by only updating outdated files .

In Java, `URLConnection` plays a critical role in establishing a connection to a URL to read or write data. When downloading webpage content, `URLConnection` facilitates obtaining an `InputStream` from the URL, which can be read using `BufferedReader`. It's important to handle potential IOExceptions that may occur during the connection or data reading processes. Correctly closing streams after data processing is vital to avoid resource leaks, and attention should be given to potential `MalformedURLException` if the URL format is incorrect .

You might also like