0% found this document useful (0 votes)
14 views18 pages

Networking

The document outlines the design and implementation of various client-server communication systems in Java using socket programming. It includes algorithms and code for different applications, such as basic message exchange, arithmetic operations, and data transmission of numeric and alphabetic characters. Each implementation demonstrates fundamental networking concepts and provides a foundation for more complex systems, highlighting the use of DataInputStream and DataOutputStream for data handling.

Uploaded by

rohit8478814385
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)
14 views18 pages

Networking

The document outlines the design and implementation of various client-server communication systems in Java using socket programming. It includes algorithms and code for different applications, such as basic message exchange, arithmetic operations, and data transmission of numeric and alphabetic characters. Each implementation demonstrates fundamental networking concepts and provides a foundation for more complex systems, highlighting the use of DataInputStream and DataOutputStream for data handling.

Uploaded by

rohit8478814385
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
You are on page 1/ 18

Problem Definition:

Design a basic client-server communication system in Java using socket programming. The client sends a
greeting to the server, and the server replies, showcasing fundamental input/output handling over a network
connection.

Algorithm:

1. Server Side (MyServer.java):


o Initialize a ServerSocket on a specific port (e.g., 7777).
o Wait for a client to connect using the accept() method.
o Read the client's message using DataInputStream.
o Respond with a message using DataOutputStream.
o Close all connections and streams once the communication ends.
2. Client Side (MyClient.java):
o Connect to the server using a Socket and the designated port.
o Use DataOutputStream to send a message to the server.
o Receive the server’s response through DataInputStream.
o Terminate the connection by closing all streams and the socket.

Implementation:

1. MyServer.java

import java.net.*;
import java.io.*;

public class MyServer {


public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(7777);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String message = dis.readUTF();
System.out.println("Client says: " + message);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello Client, your message has been received.");
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

2. MyClient.java

import java.net.*;
import java.io.*;

public class MyClient {


public static void main(String args[]) {
try {
Socket s = new Socket("localhost", 7777);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello Server");
DataInputStream dis = new DataInputStream(s.getInputStream());
String response = dis.readUTF();
System.out.println("Server replies: " + response);
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Result:

Output on Server Console:

Client says: Hello Server

Output on Client Console:

Server replies: Hello Client, your message has been received.

Discussion:

 This program demonstrates the core concepts of Java socket programming through a simple one-time
message exchange.
 It utilizes DataInputStream and DataOutputStream to transmit UTF-encoded strings across the
network.
 The server listens passively for a connection, while the client actively initiates the conversation.
 This structure provides a foundation for developing more advanced client-server systems, including
multi-threading, persistent sessions, and robust exception handling.
Problem Definition:

This project showcases a basic client-server communication model in Java using socket programming. The
client sends a text message to the server, which processes it and returns a customized acknowledgment. This
interaction serves as an introduction to Java’s networking capabilities.

Algorithm:

1. Server Side (MyServer1.java):


o Set up a ServerSocket on a specified port (e.g., 7777).
o Wait for a client to establish a connection using accept().
o Read the incoming message using DataInputStream.
o Send a confirmation response using DataOutputStream.
o Close all resources once the interaction is complete.
2. Client Side (MyClient1.java):
o Connect to the server using a Socket on the defined port.
o Use DataOutputStream to send a message to the server.
o Read the server’s response through DataInputStream.
o Close the socket and data streams to end the session.

Implementation:

1. MyServer1.java

import java.net.*;
import java.io.*;

public class MyServer1 {


public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(7777);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String received = dis.readUTF();
System.out.println("Message from client: " + received);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Received your message: \"" + received + "\". Connection
successful.");
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

2. MyClient1.java

import java.net.*;
import java.io.*;

public class MyClient1 {


public static void main(String args[]) {
try {
Socket s = new Socket("localhost", 7777);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Greetings from the client side");
DataInputStream dis = new DataInputStream(s.getInputStream());
String response = dis.readUTF();
System.out.println("Server response: " + response);
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Result:

Server Console Output:

Message from client: Greetings from the client side

Client Console Output:

Server response: Received your message: "Greetings from the client side". Connection
successful.

Discussion:

 This program demonstrates how Java’s socket API can be used for simple text-based communication.
 The server passively waits for client requests and responds with a structured message.
 DataInputStream and DataOutputStream facilitate efficient and reliable data transmission.
 This setup forms a foundational structure for more complex applications such as chat systems or
networked services.
Problem Definition:

The purpose of this application is to demonstrate how socket programming in Java can be used to perform basic
arithmetic operations in a client-server environment. The client collects input from the user — two numbers and
an operator — and sends this data to the server. The server processes the request, performs the calculation, and
sends the result back to the client.

Algorithm:

1. Server Side (Calserver.java):


o Initialize a ServerSocket on a fixed port (e.g., 6666).
o Wait for a client to connect using the accept() method.
o Use DataInputStream to read two integers and an operator from the client.
o Execute the appropriate operation based on the operator provided.
o Return the result to the client through DataOutputStream.
o Close the socket and all associated input/output streams.
2. Client Side (Calclient.java):
o Connect to the server using a Socket and the same port.
o Collect two numeric values and an operator from the user.
o Send these inputs to the server using DataOutputStream.
o Read and display the result returned by the server via DataInputStream.
o Close the connection and clean up resources.

Implementation:

1. Calserver.java

import java.io.*;
import java.net.*;
class Calserver {
public static void main(String args[]) throws Exception {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
int a = dis.readInt();
int b = dis.readInt();
char op = dis.readChar();
int result = 0;
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/': result = (b != 0) ? a / b : 0; break;
default:
dos.writeUTF("Error: Invalid Operator");
s.close(); ss.close();
return;
}
dos.writeUTF("Result = " + result);
dis.close();
dos.close();
s.close();
ss.close();
}
}

2. Calclient.java

import java.io.*;
import java.net.*;
import java.util.*;
class Calclient {
public static void main(String args[]) throws Exception {
Socket s = new Socket("localhost", 6666);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.print("Enter operator (+, -, *, /): ");
char op = sc.next().charAt(0);
dos.writeInt(a);
dos.writeInt(b);
dos.writeChar(op);
String result = dis.readUTF();
System.out.println("Result from server: " + result);
dos.close();
dis.close();
s.close();
sc.close();
}
}

Result:

Client Console Output: Enter first number: 15


Enter second number: 3
Enter operator (+, -, *, /): /
Result from server: Result = 5

Discussion:

 This program effectively demonstrates how client-server architecture can be used to perform basic
computations remotely.
 The client handles user interaction, while the server processes the logic and sends back the result.
 Using DataInputStream and DataOutputStream allows for simple transmission of primitive data
types.
 The current version is designed for single transactions; future improvements could include continuous
operation, exception handling (e.g., divide by zero), and multi-client support using threads.
Problem Definition:

Design a simple client-server system (stop and wait) in Java using socket programming. The objective is for the
server to transmit a message to the client upon establishing a connection.

Algorithm:

1. Server Side (Serversnw.java):


o Initialize a ServerSocket on a specific port (e.g., 9999).
o Listen for incoming client connections using accept().
o Create a DataOutputStream to send data to the client.
o Transmit a greeting message to the connected client.
o Close the data stream and socket once the message is sent.
2. Client Side (Clientsnw.java):
o Establish a connection to the server using its IP address and port number.
o Use a DataInputStream to receive data from the server.
o Read and print the message received from the server.
o Properly close the stream and socket after the interaction.

Implementation:

1. Serversnw.java

import java.io.*;
import java.net.*;

public class Serversnw {


public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept();

DataOutputStream dos = new DataOutputStream(s.getOutputStream());


dos.writeUTF("Hello from Server");

dos.close();
s.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

2. Clientsnw.java

import java.io.*;
import java.net.*;

public class Clientsnw {


public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 9999);

DataInputStream dis = new DataInputStream(s.getInputStream());


String msg = dis.readUTF();
System.out.println("Server says: " + msg);

dis.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Result:

Sample Output (Server Console):

(The server silently sends a message to the client – no direct console output.)

Sample Output (Client Console):

Server says: Hello from Server

Discussion:

 This program illustrates a basic use case of Java socket programming to exchange messages.
 Communication is handled using DataInputStream and DataOutputStream.
 The server sends a predefined message upon successful connection, which the client receives and prints.
 The project can be enhanced to include features like bidirectional messaging, multi-client support, or
threaded server handling.
Problem Definition:

Build a Java client-server application using socket communication. The server's task is to send a message
containing numeric digits and uppercase alphabets to the client, which then prints the message.

Algorithm:

1. Server Side (Serverabcd.java):


o Set up a ServerSocket on port 5555.
o Wait for a client to initiate a connection using accept().
o Create a DataOutputStream to transmit data.
o Send a predefined string containing numbers and capital letters.
o Close the output stream and sockets after the message is delivered.
2. Client Side (Clientabcd.java):
o Connect to the server using the given host and port.
o Use a DataInputStream to receive data.
o Read the message from the server and display it on the console.
o Terminate the connection by closing the stream and socket.

Implementation:

1. Serverabcd.java

import java.io.*;
import java.net.*;

public class Serverabcd {


public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(5555);
Socket s = ss.accept();

DataOutputStream dos = new DataOutputStream(s.getOutputStream());


dos.writeUTF("1234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZ");

dos.close();
s.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

2. Clientabcd.java

import java.io.*;
import java.net.*;

public class Clientabcd {


public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 5555);

DataInputStream dis = new DataInputStream(s.getInputStream());


String message = dis.readUTF();
System.out.println("Server says: " + message);

dis.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Result:

Server Output (Console):

(No visible output; the server sends data to the client)

Client Output (Console):

Server says: 1234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZ

Discussion:

 This program highlights a basic implementation of socket-based communication.


 It uses DataOutputStream and DataInputStream to handle UTF-encoded strings.
 The server transmits a single-line static message which the client displays.
 The program can be enhanced with dynamic data generation, two-way communication, or concurrent
client handling using threads.
Problem Definition:
This project illustrates a simple client-server communication setup using Java socket programming. The
server listens on a specific port and responds to incoming client messages. The client initiates a connection,
sends a message, and receives a reply from the server. This exercise serves as a foundational introduction to
Java’s networking capabilities.

Algorithm:
1. Server Side (Server.java) 2. Client Side (Client.java)
 Create a ServerSocket bound to port 5000.  Establish a connection to the server using a
 Wait for a client connection using accept(). Socket.
 Read incoming data from the client using  Send a message to the server via
BufferedReader. PrintWriter.
 Print the received message on the server  Read the server’s response using
console. BufferedReader.
 Send a response back to the client using  Display the response on the client console.
PrintWriter.  Close the socket and associated streams.
 Close all open resources after
communication is complete.

Implementation:
1. Server.java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println("Client says: " + str);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println("Message received. Hello from Server!");
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

2. Client.java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[]) {
try {
Socket s = new Socket("localhost", 5000);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println("Hello Server, I am the Client!");
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println("Server says: " + str);
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Result:
Server Output: Client Output:
Client says: Hello Server, I am the Client! Server says: Message received. Hello from
Server!

Discussion:
 This project demonstrates how Java sockets can be used to build a basic communication channel
between a server and a client.
 The use of BufferedReader and PrintWriter simplifies reading and writing string data over the
network.
 The server handles a single client session and responds with a predefined message.
 This basic architecture can be extended to support multi-client communication, request handling, or
real-time applications like chat systems.
Problem Definition:
This experiment demonstrates the simulation of the Selective Repeat Automatic Repeat reQuest (ARQ)
protocol using Java. Selective Repeat ARQ is a reliable data transfer method that ensures only those frames
which are lost or corrupted during transmission are retransmitted. The system comprises two components: a
sender and a receiver, which communicate using simulated frame transfers and acknowledgments.

Algorithm:
1. Sender (SRs.java) 2. Receiver (SRc.java)

 Prompt the user to specify the total number  Accept frames sent by the sender.
of frames to be transmitted.  Simulate potential frame loss by prompting
 Transmit each frame sequentially to the the user to verify whether each frame was
receiver. received correctly.
 Wait for an acknowledgment (ACK) for  If a frame is deemed lost or incorrect, notify
each frame. the sender to retransmit it.
 If the receiver indicates frame loss (via  Send an acknowledgment for each
NACK or absence of ACK), retransmit only successfully received frame.
that specific frame.  Repeat until all frames are correctly
 Continue the process until all frames are received.
successfully acknowledged.

Implementation:
Sender – SRs.java
import java.io.*;
import java.net.*;
import java.util.*;
public class SRs {
public static void main(String args[]) throws Exception {
Socket s = new Socket("localhost", 6666);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
DataInputStream din = new DataInputStream(s.getInputStream());
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of frames: ");
int n = sc.nextInt();
dout.write(n);
for (int i = 0; i < n; i++) dout.write(i);
for (int i = 0; i < n; i++) {
int ack = din.read();
if (ack == -1) {
System.out.println("Resending frame " + i); dout.write(i); i--; //
Decrement to retransmit
} else {
System.out.println("Acknowledgment received for frame " + i);
}
}
sc.close(); dout.close(); din.close(); s.close();
}
}
Receiver – SRc.java
import java.io.*;
import java.net.*;
import java.util.*;
public class SRc {
public static void main(String args[]) throws Exception {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
Scanner sc = new Scanner(System.in);
int n = din.read();
for (int i = 0; i < n; i++) {
int frame = din.read();
System.out.println("Frame received: " + frame);
System.out.print("Was this frame received correctly? (yes/no): ");
String status = sc.next();
if (status.equalsIgnoreCase("yes")) dout.write(1); // ACK
else {
dout.write(-1); // NACK
i--; // Wait to re-receive the frame
}
}

sc.close(); din.close(); dout.close(); s.close(); ss.close();


}
}

Result:
Sender Output (Sample): Receiver Output (Sample):
Enter number of frames: 4 Frame received: 0
Acknowledgment received for frame 0 Was this frame received correctly? yes
Acknowledgment received for frame 1 Frame received: 1
Resending frame 2 Was this frame received correctly? yes
Acknowledgment received for frame 2 Frame received: 2
Acknowledgment received for frame 3 Was this frame received correctly? no
Frame received: 2
Was this frame received correctly? yes
Frame received: 3
Was this frame received correctly? yes

Discussion:
 The simulation effectively demonstrates the working of the Selective Repeat ARQ protocol, focusing on
reliability by selectively retransmitting erroneous frames rather than the entire sequence.
 The sender maintains the order of frames and manages retransmission based on acknowledgments from
the receiver.
 User interaction is used to simulate errors and acknowledgment loss, providing an interactive
understanding of the protocol.
 Though this is a basic, text-based model, it accurately represents the core mechanism of Selective
Repeat ARQ.
Problem Definition:
This project involves the development of a basic Domain Name System (DNS) simulation using Java. The
application allows users to input a domain name and retrieves the corresponding IP address from a predefined
static mapping. The purpose of this simulation is to demonstrate the fundamental principles of DNS resolution
in a simplified, offline environment.

Algorithm:
1. Create a HashMap to store key-value pairs of domain names and their corresponding IP addresses.
2. Prompt the user to enter a domain name.
3. Search the map for the given domain:
o If the domain exists, return the associated IP address.
o If not, display a message indicating the domain is not found.
4. Continue to prompt the user for new domain names until the user chooses to exit the program.

Implementation:
DNS.java
import java.util.*;

public class DNS {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Static DNS mapping


HashMap<String, String> dnsTable = new HashMap<>();
dnsTable.put("www.google.com", "142.250.183.68");
dnsTable.put("www.facebook.com", "157.240.22.35");
dnsTable.put("www.youtube.com", "142.250.180.206");
dnsTable.put("www.twitter.com", "104.244.42.1");

System.out.println("=== DNS Simulator ===");

while (true) {
System.out.print("\nEnter domain name (or type 'exit' to quit): ");
String domain = sc.nextLine();

if (domain.equalsIgnoreCase("exit")) {
System.out.println("Exiting DNS Simulator.");
break;
}

if (dnsTable.containsKey(domain)) {
System.out.println("IP Address: " + dnsTable.get(domain));
} else {
System.out.println("Domain not found in DNS records.");
}
}

sc.close();
}
}

Result:
Sample Output:
=== DNS Simulator ===

Enter domain name (or type 'exit' to quit): www.google.com


IP Address: 142.250.183.68

Enter domain name (or type 'exit' to quit): www.unknownsite.com


Domain not found in DNS records.

Enter domain name (or type 'exit' to quit): exit


Exiting DNS Simulator.

Discussion:
 This program provides a simple simulation of DNS name resolution using an internal lookup table.
 It demonstrates how domain names can be mapped to IP addresses without using actual network queries.
 The use of a HashMap ensures fast and efficient retrieval of records.
 The system supports continuous interaction until the user exits, offering a user-friendly loop-based
design.
 Although simplified, this simulation effectively illustrates the core functionality of DNS.
 Possible extensions to this project include:
o Reading DNS records from external sources (files or databases).
o Adding support for real-time DNS resolution using Java’s InetAddress class.
o Introducing hierarchical lookup simulation to better reflect real DNS behavior.
o Enabling dynamic updates to the DNS record set.
Problem Definition:
This program aims to build a Java client-server app using sockets for string manipulation. The client sends a
string and an operation (e.g., reverse, concatenate, case conversion), and the server returns the processed result.

Algorithm:

1. Server Side (Serverstr.java): 2. Client Side (Clientstr.java):

 Create a ServerSocket on a specified port  Establish a socket connection to the server at


(e.g., 6666). the specified address and port.
 Accept a client connection using accept().  Collect user input for the string and the
 Use DataInputStream and operation to be performed.
DataOutputStream for socket  Transmit this data to the server via
communication. DataOutputStream.
 Receive a string and a command indicating  Receive the modified string from the server
the operation (rev, concat, uppercase, using DataInputStream.
lowercase, sentence).  Display the result to the user.
 Perform the specified string manipulation.  Properly close the connection and all
 Send the result back to the client. associated resources.
 Close the streams and socket.

Implementation:

1. Serverstr.java
import java.io.*;
import java.net.*;
public class Serverstr {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
String str = dis.readUTF();
String op = dis.readUTF();
String result = "";
switch (op.toLowerCase()) {
case "rev":
result = new StringBuilder(str).reverse().toString();
break;
case "concat":
result = str + str;
break;
case "uppercase":
result = str.toUpperCase();
break;
case "lowercase":
result = str.toLowerCase();
break;
case "sentence":
result = str.substring(0, 1).toUpperCase() +
str.substring(1).toLowerCase();
break;
default:
result = "Invalid Operation";
}
dos.writeUTF(result);
dis.close();
dos.close();
s.close();
ss.close();
}
}

2. Clientstr.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Clientstr {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 6666);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
System.out.print("Enter operation (rev, concat, uppercase, lowercase, sentence):
");
String op = sc.nextLine();
dos.writeUTF(input);
dos.writeUTF(op);
String response = dis.readUTF();
System.out.println("Server Response: " + response);
dis.close();
dos.close();
s.close();
sc.close();
}
}

Result:

Client Console Output Example:


Enter a string: HELLO WORLD Server Console Output:
Enter operation (rev, concat, uppercase, (The server performs background
lowercase, sentence): lowercase operations; no direct console output)
Server Response: hello world

Discussion:
 This program showcases the fundamental concepts of socket programming in Java, applied to string
processing.
 It enables a range of string operations by transmitting data between client and server using
DataInputStream and DataOutputStream.
 The system supports five operations: reversing, concatenation, and character case conversions.
 The implementation can be further enhanced to support continuous multi-request sessions, error
handling (e.g., null strings), or multi-client handling.
 Additional functionalities or a graphical user interface (GUI) can also be incorporated to improve user
experience.

You might also like