Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Name:Suyash Jadhav

ID:vu1f2021100
DIV:B Batch:C
Distributed Computing

Experiment No.2

Server Side:
import java.io.BufferedReader; import
java.io.IOException; import
java.io.InputStreamReader; import
java.net.ServerSocket; import java.net.Socket;
import java.util.Date; public class Server {
public static void main(String[] args) {
try {
// Create a server socket on port 12345

ServerSocket serverSocket = new ServerSocket(12345);

System.out.println("Server is waiting for client


connection...");
// Wait for a client to connect

Socket clientSocket = serverSocket.accept();

System.out.println("Client connected!");
// Create input stream to read data from the client

BufferedReader reader = new BufferedReader(new

InputStreamReader(clientSocket.getInputStream()));
// Read data from the client

String clientMessage = reader.readLine();

System.out.println("Received from client: " +


clientMessage);

// Process the data (in this example, we just append a


timestamp)

String response = "Server response: " + clientMessage + "


at " + new Date();

// Send the response back to the client


clientSocket.getOutputStream().write(response.getBytes());
// Close the sockets
clientSocket.close(); serverSocket.close();
} catch (IOException e) {
Name:Suyash Jadhav
ID:vu1f2021100
DIV:B Batch:C
Distributed Computing

e.printStackTrace();

Client Side:
import java.io.BufferedReader; import
java.io.IOException; import
java.io.InputStreamReader; import
java.net.Socket; public class Client {
public static void main(String[] args) {
try {
// Connect to the server on localhost and port 12345

Socket socket = new Socket("localhost", 12345); // Create


output stream to send data to the server
socket.getOutputStream().write("Hello Server!".getBytes());
// Create input stream to read data from the server

BufferedReader reader = new BufferedReader(new

InputStreamReader(socket.getInputStream()));
// Read the response from the server

String serverResponse = reader.readLine();

System.out.println("Received from server: " + serverResponse);


// Close the socket
socket.close(); } catch
(IOException e) {
e.printStackTrace();

}
Name:Suyash Jadhav
ID:vu1f2021100
DIV:B Batch:C
Distributed Computing

OUTPUT:

You might also like