Experiment- 2
Class: B Tech/ MBA Tech Branch: CE/CS Sem-VI
Part A
Aim: Socket programming:
a) Implement client-server application for sending message .
b) Implement client-server application for one way communication.
c) Implement client-server application for two way communication (chat application )
Prerequisite: Computer network and operating system, Port number, IP address.
Outcome: To impart knowledge of distributed system and Socket Programming.
Theory:
A socket is one end-point of a two-way communication link between two programs running
on the network. Socket classes are used to represent the connection between a client program
and a server program.
The chat system consists of two distributed components: chat server and chat client, which
may run on different hosts in the network. We provide you the server side of the system. We
also provide a skeleton of the chat client that includes a simple user interface to allow users of
the chat client to type in control commands and chat messages. You must add client support
for all communication, including
requesting chat server location
information from a location server, the
exchange of control messages with the
server, and the display of received chat
messages. Finally, your chat client must
detect chat server failures and attempt a
simple form of recovery.
The chat server conducts a chat session
in chat rooms. At any given time there
may be multiple chat clients in a chat
session. The chat server is responsible
for managing all the chat clients in the
session and distributing chat messages. A
chat client starts by requesting the
communication parameters (server name
and port numbers) for the chat server
from a location server.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket
to a server.
When the connection is made, the server creates a socket object on its end of the
communication. The client and server can now communicate by writing to and reading from
the socket.
The following steps occur when establishing a TCP connection between two computers using
sockets:
The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server
name and port number to connect to.
The constructor of the Socket class attempts to connect the client to the specified
server and port number. If communication is established, the client now has a Socket
object capable of communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the
server that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each
socket has both an OutputStream and an InputStream. The client's OutputStream is connected
to the server's InputStream, and the client's InputStream is connected to the server's
OutputStream.
TCP is a two way communication protocol, so data can be sent across both streams at the
same time. There are following useful classes providing complete set of methods to
implement sockets.
Procedure:
Step 1: A simple server that will accept a single client connection and display
everything the client says on the screen. If the client user types ".bye", the client and
the server will both quit.
Step 2: A server as before, but this time it will remain 'open' for additional connection
once a client has quit. The server can handle at most one connection at a time.
Step 3: A server as before, but this time it can handle multiple clients simultaneously.
The output from all connected clients will appear on the server's screen.
Step 4: A server as before, but this time it sends all text received from any of the
connected clients to all clients. This means that the server has to receive and send, and
the client has to send as well as receive
Step 5: Wrapping the client from step 4 into a very simple GUI interface but not
changing the functionality of either server or client.
Instructions:
1. Write program in Java.
2. Use inbuilt packages for socket programming.
Part B
(TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on portal )
Roll No. : N239 Name: AKSHANSH SHRIVASTAVA
Sem/Year : VI 3rd Yr Batch: B DIV
Date of Experiment : Date of Submission:
Grade -- Group No.:
Code:
a) Client-Server Application for Sending Messages:
Server (ServerSendMessage.java):
import java.io.*;
import java.net.*;
public class ServerSendMessage {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server listening on port 12345...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println("Hello, client! This is a message from the server.");
out.close();
clientSocket.close();
serverSocket.close();
}
}
Client (ClientSendMessage.java):
import java.io.*;
import java.net.*;
public class ClientSendMessage {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String message = in.readLine();
System.out.println("Received message from server: " + message);
in.close();
socket.close();
}
}
b) Client-Server Application for One-Way Communication:
Server (ServerOneWay.java):
import java.io.*;
import java.net.*;
public class ServerOneWay {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server listening on port 12345...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String message = in.readLine();
System.out.println("Received message from client: " + message);
in.close();
clientSocket.close();
serverSocket.close();
}
}
Client (ClientOneWay.java):
import java.io.*;
import java.net.*;
public class ClientOneWay {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello, server! This is a one-way communication message.");
out.close();
socket.close();
}
}
c) Client-Server Application for Two-Way Communication (Chat Application):
Server (ServerChat.java):
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ServerChat {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server listening on port 12345...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
// Start a thread to handle client messages
Thread clientThread = new Thread(new ClientHandler(clientSocket));
clientThread.start();
// Accept messages from the server console and send to the client
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
while (true) {
String serverMessage = scanner.nextLine();
out.println(serverMessage);
}
}
}
class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
while (true) {
String clientMessage = in.readLine();
System.out.println("Received message from client: " + clientMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client (ClientChat.java):
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ClientChat {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
// Start a thread to handle server messages
Thread serverThread = new Thread(new ServerHandler(socket));
serverThread.start();
// Accept messages from the client console and send to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
while (true) {
String clientMessage = scanner.nextLine();
out.println(clientMessage);
}
}
}
class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
while (true) {
String serverMessage = in.readLine();
System.out.println("Received message from server: " + serverMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Input & Output:
Observation & Learning:
Sockets enable computer communication via networks. Servers wait, clients connect,
facilitating data exchange. Programs manage one-way or two-way interactions, handling
errors and ensuring security.
Write your Observations & Learning after performing task
Conclusion:
Understanding sockets facilitates computer communication over networks, allowing servers to
wait for connections and clients to initiate them, enabling data exchange. Programs can
manage one-way or two-way interactions, implementing error handling and security measures
for stable, secure communication.
Questions: (Write answers)
1. Why we use Socket Programming?
Socket programming is used for communication between processes over a network. It
enables inter-process communication, facilitates network communication, and is
crucial for client-server architectures. Sockets are fundamental for real-time
communication, file transfer, and the implementation of network protocols. They play
a key role in web development, IoT applications, and the creation of custom network
protocols. Socket programming is versatile, supporting a range of applications where
devices need to exchange data and coordinate activities.
2. What are the different System Architectures?
System architectures refer to the structural design of a computer system
or a network, outlining how components are organized and interact to
achieve specific functionalities. There are several types of system
architectures, each serving different purposes. Here are some common
types:
1. Single-Tier Architecture (Monolithic):
In a single-tier architecture, also known as monolithic
architecture, all the components of the application reside on a
single machine. This design is straightforward but lacks
scalability and can become complex as the application grows.
2. Two-Tier Architecture (Client-Server):
Two-tier architecture involves dividing the application into two
parts: a client, responsible for the user interface and
application processing, and a server, handling the database
and business logic. This architecture allows for better
organization and scalability compared to single-tier systems.
3. Three-Tier Architecture:
Three-tier architecture further separates the application into
three components: the presentation layer (client), application
logic layer (server), and data storage layer (database). This
design enhances modularity, maintainability, and scalability
compared to two-tier architectures.
4. N-Tier Architecture:
N-tier architecture extends the concept of three-tier
architecture by introducing additional layers for specific
functionalities. This design provides greater flexibility, allowing
for the distribution of components across multiple servers and
improving scalability and maintainability.
5. Microservices Architecture:
Microservices architecture structures an application as a
collection of small, independent services, each running in its
own process and communicating with lightweight mechanisms
(e.g., HTTP or messaging protocols). This approach enhances
scalability, fault isolation, and ease of deployment and
maintenance.
6. Service-Oriented Architecture (SOA):
SOA is an architectural pattern where components are
organized as services that can be accessed and utilized
independently. These services communicate with each other
over a network, typically using web services protocols. SOA
promotes reusability and flexibility.
7. Event-Driven Architecture (EDA):
Event-Driven Architecture involves the production, detection,
consumption, and reaction to events. Components
communicate asynchronously through events, making the
system responsive to changes. EDA is common in real-time
and reactive systems.
8. Peer-to-Peer Architecture (P2P):
In a peer-to-peer architecture, each node in the network has
equal status, and there is no central server. Nodes
communicate directly with each other, sharing resources and
distributing tasks. P2P is often used in file-sharing and
distributed computing.
9. Cloud-Based Architecture:
Cloud-based architecture leverages cloud computing resources
and services to build, host, and scale applications. It enables
on-demand access to computing resources, enhances
scalability, and reduces the need for physical infrastructure.
10. Distributed Architecture:
Distributed architecture involves the distribution of
components across multiple computers that communicate
through a network. This approach improves fault tolerance,
performance, and scalability but requires effective
coordination and communication.
These architectures vary in complexity, scalability, and suitability for
different types of applications. The choice of architecture depends on
factors such as application requirements, scalability needs, and
development goals.
3. Client-server architecture comes in which category of system architecture?
Client-server architecture falls under the category of Two-Tier Architecture or N-Tier
Architecture depending on the specific design. It is characterized by the division of the
application into two main components: the client and the server.
In a typical client-server architecture:
Client: The client is responsible for the user interface, presentation logic, and user
interaction. It may run on the user's device, such as a computer or mobile device.
Server: The server handles the business logic, application processing, and data storage.
It is responsible for processing client requests, executing business logic, and managing
access to the data storage.
This architecture allows for a clear separation of concerns, making it easier to
maintain, scale, and update the application. It also enables multiple clients to interact
with a centralized server, facilitating shared resources and data.
If additional layers, such as a separate database layer, are introduced, the architecture
may be considered as an N-Tier Architecture. The number of tiers increases based on
the complexity and separation of components within the application.