0% found this document useful (0 votes)
38 views25 pages

Ex No 6 CN

The document describes how to implement a single client-server chatting application using both connection-oriented and connectionless sockets in Java. It provides explanations of key concepts like TCP vs UDP, IP addresses and port numbers. It also lists the main methods available for TCP and UDP socket programming in Java.

Uploaded by

b29012005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views25 pages

Ex No 6 CN

The document describes how to implement a single client-server chatting application using both connection-oriented and connectionless sockets in Java. It provides explanations of key concepts like TCP vs UDP, IP addresses and port numbers. It also lists the main methods available for TCP and UDP socket programming in Java.

Uploaded by

b29012005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

22IT012

Ex No 6 Implementation of single client-server chatting application using


Connection-oriented and Connectionless sockets
15/03/2024

Aim:

To implement a single client-server chatting application using Connection-oriented and


Connectionless sockets in Java

To use Socket programming for developing client/server application for Customer Management
service

Theory:

1. Connection Oriented Vs. Connection less Service

Connection Oriented Connection less

Connection-oriented service is Connection-less Service is preferred


preferred by long and steady by bursty communication.
communication.

Connection-oriented Service is Connection-less Service is not


feasible. feasible.

Connection-oriented Service gives the Connection-less Service does not give


guarantee of reliability. a guarantee of reliability.

In connection-oriented Service, In connection-less Service, Packets do


Packets follow the same route. not follow the same route.

Ex: TCP (Transmission Control Ex: UDP (User Datagram Protocol)


Protocol)

2. Reliable Vs. Unreliable Service

Reliable Unreliable

Guaranteed Delivery: Reliable No Guarantees: Unreliable


communication protocols, such as TCP, communication protocols, such as UDP,
ensure that data packets reach the do not provide assurances regarding data
destination in the correct order and delivery. Packets may be lost, arrive out
without errors. This is achieved through of order, or be duplicated.
acknowledgment mechanisms,
retransmissions of lost packets, and
sequencing of packets.

Error Detection and Correction: Reliable No Error Correction: Unreliable protocols

1
22IT012

protocols include error detection and do not include error correction


correction mechanisms to identify and fix mechanisms. Any errors that occur during
errors that may occur during transmission are not corrected, and the
transmission. receiver must handle them as they occur.

Ordered Delivery: Data packets are No Acknowledgments or


delivered in the same order in which they Retransmissions: Unreliable protocols do
were sent. not use acknowledgments or
retransmissions to ensure data delivery.
Once a packet is sent, the sender does not
wait for acknowledgment before sending
the next packet.

Flow Control: Reliable protocols No Flow Control: Unreliable protocols do


implement flow control mechanisms to not implement flow control mechanisms.
regulate the data transmission rate and As a result, there is a risk of
prevent overwhelming the receiver or overwhelming the receiver or congesting
congesting the network. the network if data is sent too quickly.

Connection-Oriented: Reliable protocols Connectionless: Unreliable protocols are


typically establish a connection between typically connectionless, meaning they do
the sender and receiver before data not establish a connection before data
transfer, ensuring a reliable channel for transfer. Each packet is treated
communication. independently, and there is no concept of
a continuous communication channel.

3. IP Address:
● An IP address (Internet Protocol address) is a numerical label assigned to each
device connected to a computer network that uses the Internet Protocol for
communication.IP addresses are used for various purposes, including identifying
the source and destination of data packets on a network, routing data across the
Internet, and providing location information for devices. They are essential for
the functioning of the Internet and other computer networks.
4. Port number:
● A port number is a 16-bit unsigned integer used to uniquely identify specific
communication endpoints, or network services, within a host in a computer
network. In the Internet Protocol (IP) context, port numbers are combined with
IP addresses to specify the destination or source of data packets.
5. Any 6 methods available in Java for TCP/Connection oriented sockets with explanations
○ ServerSocket:
■ The ServerSocket class is used to create a server-side socket that
listens for incoming TCP connections on a specific port.
■ You can use the accept() method of ServerSocket to accept
incoming connections and obtain a Socket object for
communication with the client.
○ Socket:

2
22IT012

■The Socket class represents a client-side endpoint of a two-way


communication link between a client and a server.
■ You can create a Socket object by providing the server's IP
address and port number to establish a connection.
○ InputStream and OutputStream:
■ Once a connection is established using Socket, you can obtain
input and output streams to send and receive data between client
and server.
■ Use getInputStream() and getOutputStream() methods of Socket
to get input and output streams, respectively.

o BufferedReader and BufferedWriter:
■ To read and write text-based data over TCP connections, you can
wrap input and output streams with BufferedReader and
BufferedWriter.
■ These classes provide convenient methods for reading and
writing lines of text.
■ DataInputStream and DataOutputStream:
● If you need to read and write primitive data types (e.g.,
int, double) over TCP connections, you can use
DataInputStream and DataOutputStream.
● These classes provide methods for reading and writing
primitive data types directly
○ Close Method:
To release system resources and close the connection, always call
the close() method on sockets, server sockets, and streams when
you're done with them

6. Any 6 methods available in Java for UDP/Connection less sockets with explanations

o DatagramSocket:
 The DatagramSocket class is used to create a socket for
sending and receiving datagrams (packets) over a UDP
connection.
 You can create a DatagramSocket object to send and
receive datagrams on a specific port.
o DatagramPacket:
 The DatagramPacket class represents a packet of data to
be sent or received over a UDP connection.
 You can create a DatagramPacket object to encapsulate
data, along with the destination IP address and port.
o send() Method:
 The send() method of DatagramSocket is used to send a
DatagramPacket over the UDP connection.
 You can use this method to send datagrams to a specific
destination.

3
22IT012

o receive() Method:
 The receive() method of DatagramSocket is used to receive a
DatagramPacket over the UDP connection.
 You can use this method to receive datagrams sent by remote
hosts.
o getData() and setData() Methods:
 The getData() method of DatagramPacket retrieves the data
from the packet.
 The setData() method of DatagramPacket sets the data to be
sent in the packet.
o Close Method:
 As with TCP, always call the close() method on sockets to
release system resources after you're done using them.

Algorithm:

Chat Application using UDP:

Server Initialization:

1. Create a DatagramSocket object on a specific port to listen for incoming


messages.
2. Print a message indicating that the server is running.

Client Initialization:

1. Create a DatagramSocket object to send and receive messages.


2. Prompt the user to enter the server's IP address and port number.
3. Start a loop to continuously send and receive messages.

Sending Messages (Client):

1. Prompt the user to enter a message.


2. Convert the message to bytes.
3. Create a DatagramPacket with the message bytes, server's IP address, and
port number.
4. Send the packet using the client socket.

Receiving Messages (Server):

1. Create a buffer to store received message bytes.


2. Create a DatagramPacket to receive messages.
3. Use the server socket to receive the packet.

4
22IT012

4. Extract the message from the packet and print it to the console.

Repeat:

 Go back to step 3 for the client and step 4 for the server.

Close Sockets:

 Close the sockets when the communication is finished

Chat Application using TCP:

Server Initialization:

1. Create a ServerSocket object on a specific port to listen for incoming


connections.
2. Print a message indicating that the server is running.

Client Initialization:

1. Create a Socket object to connect to the server's IP address and port number.
2. Start a loop to continuously send and receive messages.

Sending Messages (Client):

1. Prompt the user to enter a message.


2. Create an OutputStreamWriter to send messages over the socket's output
stream.
3. Write the message to the output stream.
4. Flush the output stream to ensure the message is sent immediately.

Receiving Messages (Server):

1. Accept incoming connections using the accept() method of ServerSocket.


2. Create an InputStreamReader to read messages from the socket's input
stream.
3. Read the message from the input stream.
4. Print the received message to the console.

Repeat:

 Go back to step 3 for both the client and the server.

5
22IT012

Close Sockets:

 Close the sockets when the communication is finished.

Client/Server Application for Customer Management service using TCP

1. Server Initialization:
 Create a ServerSocket object and bind it to a specific port (12345 in this
case).
 Print a message indicating that the server is running.
2. Accepting Client Connections:
 Inside an infinite loop, wait for incoming client connections using the
accept() method of ServerSocket.
 Once a client connection is established, print the client's IP address.
3. Object Streams Initialization:
 Create ObjectInputStream and ObjectOutputStream for the client
socket's input and output streams, respectively.
4. Receiving and Processing Data:
 Inside an inner loop (for each client connection), continuously receive
Customer objects from the client using the ObjectInputStream's
readObject() method.
 Print the received Customer object to the console.
 Echo back the received Customer object to the client by writing it to
the ObjectOutputStream's output stream using the writeObject()
method.
5. Error Handling and Cleanup:
 Catch and handle IOException and ClassNotFoundException if they
occur during socket operations or object deserialization.
 Close the ServerSocket in a finally block to release the port after the
server finishes execution.

Client/Server Application for Customer Management service using UDP

1. Server Initialization:
 Create a DatagramSocket object and bind it to a specific port (e.g.,
12345).
 Print a message indicating that the server is running.
2. Receiving and Processing Data:
 Inside an infinite loop, wait to receive DatagramPackets containing data
from clients using the receive() method of DatagramSocket.
 Extract the data from the received DatagramPacket and process it (in
this case, echoing back the received message).

6
22IT012

3. Sending Response:
 Create a new DatagramPacket containing the response message.
 Set the packet's destination address and port to match the address and
port of the client from which the original packet was received.
 Send the response packet back to the client using the
DatagramSocket's send() method.
4. Error Handling and Cleanup:
 Catch and handle any IOExceptions that may occur during socket
operations.
 Optionally, handle malformed or unexpected packets received from
clients.
 Close the DatagramSocket in a finally block to release the port after the
server finishes execution.

Coding:

Chat application using UDP:

// Server.java

import java.io.*;

import java.net.*;

public class Server {

public static void main(String[] args) {

DatagramSocket socket = null;

try {

socket = new DatagramSocket(12345); // Server listens on port 12345

System.out.println("Server is running...");

while (true) {

byte[] receiveData = new byte[1024];

byte[] sendData = new byte[1024];

DatagramPacket receivePacket = new

DatagramPacket(receiveData, receiveData.length);

socket.receive(receivePacket);

InetAddress clientAddress =

7
22IT012

receivePacket.getAddress();

int clientPort = receivePacket.getPort();

String message = new

String(receivePacket.getData()).trim();

System.out.println("Client [" + clientAddress +

":" + clientPort + "] says: " + message);

BufferedReader reader = new

BufferedReader(new InputStreamReader(System.in));

String replyMessage = reader.readLine();

sendData = replyMessage.getBytes();

DatagramPacket sendPacket = new

DatagramPacket(sendData, sendData.length,

clientAddress, clientPort);

socket.send(sendPacket);

} catch (IOException e) {

e.printStackTrace();

} finally {

if (socket != null)

socket.close();

// Client.java

import java.io.*;

import java.net.*;

public class Client {

public static void main(String[] args) {

8
22IT012

DatagramSocket socket = null;

try {

InetAddress serverAddress =

InetAddress.getByName("localhost"); // Server's IP address

int serverPort = 12345; // Server's port

socket = new DatagramSocket();

System.out.println("Client is running...");

while (true) {

byte[] sendData = new byte[1024];

byte[] receiveData = new byte[1024];

BufferedReader reader = new

BufferedReader(new InputStreamReader(System.in));

String message = reader.readLine();

sendData = message.getBytes();

DatagramPacket sendPacket = new

DatagramPacket(sendData, sendData.length,

serverAddress, serverPort);

socket.send(sendPacket);

DatagramPacket receivePacket = new

DatagramPacket(receiveData, receiveData.length);

socket.receive(receivePacket);

String replyMessage = new

String(receivePacket.getData()).trim();

System.out.println("Server says: " +

replyMessage);

} catch (IOException e) {

e.printStackTrace();

9
22IT012

} finally {

if (socket != null)

socket.close();

Chat Application using TCP

//Server2.java

import java.io.*;

import java.net.*;

public class Server2 {

public static void main(String[] args) {

ServerSocket serverSocket = null;

Socket clientSocket = null;

PrintWriter out = null;

BufferedReader in = null;

try {

serverSocket = new ServerSocket(12345); // Server listens on port 12345

System.out.println("Server is running...");

clientSocket = serverSocket.accept(); // Accepts incoming client connection

System.out.println("Client connected: " + clientSocket);

out = new PrintWriter(clientSocket.getOutputStream(), true);

in = new BufferedReader(new

InputStreamReader(clientSocket.getInputStream()));

String inputLine;

BufferedReader reader = new

BufferedReader(new InputStreamReader(System.in));

while ((inputLine = in.readLine()) != null) {

10
22IT012

System.out.println("Client: " + inputLine);

String replyMessage = reader.readLine();

out.println(replyMessage);

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (out != null)

out.close();

if (in != null)

in.close();

if (clientSocket != null)

clientSocket.close();

if (serverSocket != null)

serverSocket.close();

} catch (IOException e) {

e.printStackTrace();

//Client2.java

import java.io.*;

import java.net.*;

public class Client2 {

public static void main(String[] args) {

Socket socket = null;

11
22IT012

PrintWriter out = null;

BufferedReader in = null;

try {

socket = new Socket("localhost", 12345); // Connects to server running on localhost at port


12345

out = new PrintWriter(socket.getOutputStream(), true);

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

String userInput;

while ((userInput = reader.readLine()) != null) {

out.println(userInput);

System.out.println("Server: " + in.readLine());

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (out != null)

out.close();

if (in != null)

in.close();

if (socket != null)

socket.close();

} catch (IOException e) {

e.printStackTrace();

12
22IT012

Customer application using UDP:

//Client.java

import java.io.*;

import java.net.*;

public class Client {

public static void main(String[] args) {

Socket socket = null;

ObjectOutputStream oos = null;

ObjectInputStream ois = null;

try {

InetAddress serverAddress = InetAddress.getByName("localhost");

int serverPort = 12345;

// Connect to the server

socket = new Socket(serverAddress, serverPort);

System.out.println("Client is running...");

// Create object streams for sending and receiving objects

oos = new ObjectOutputStream(socket.getOutputStream());

ois = new ObjectInputStream(socket.getInputStream());

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

while (true) {

System.out.println("Enter customer details:");

System.out.print("Name: ");

String name = reader.readLine();

13
22IT012

System.out.print("Address: ");

String address = reader.readLine();

System.out.print("Phone Number: ");

double phoneNumber = Double.parseDouble(reader.readLine());

System.out.print("Enter the amount: ");

int amount = Integer.parseInt(reader.readLine());

// Create a Customer object with the provided details

Customer customer = new Customer(name, address, phoneNumber);

customer.input(amount);

// Send the Customer object to the server

oos.writeObject(customer);

oos.flush();

// Receive response from the server

String replyMessage = (String) ois.readObject();

System.out.println("Server says: " + replyMessage);

} catch (IOException | ClassNotFoundException e) {

e.printStackTrace();

} finally {

try {

if (ois != null) ois.close();

if (oos != null) oos.close();

if (socket != null) socket.close();

} catch (IOException e) {

e.printStackTrace();

14
22IT012

//Server.java

import java.io.*;

import java.net.*;

public class Server {

public static void main(String[] args) {

ServerSocket serverSocket = null;

try {

serverSocket = new ServerSocket(12345);

System.out.println("Server is running...");

while (true) {

// Accept incoming client connection

Socket clientSocket = serverSocket.accept();

System.out.println("Client connected: " +


clientSocket.getInetAddress().getHostAddress());

// Create object streams for sending and receiving objects

ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());

ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());

while (true) {

// Receive Customer object from the client

Customer customer = (Customer) ois.readObject();

System.out.println("Received from client: " + customer.toString());

15
22IT012

// Process the received customer data (here, just echoing back)

String replyMessage = customer.toString();

oos.writeObject(replyMessage);

oos.flush();

} catch (IOException | ClassNotFoundException e) {

e.printStackTrace();

} finally {

try {

if (serverSocket != null) serverSocket.close();

} catch (IOException e) {

e.printStackTrace();

//Customer.java

import java.io.Serializable;

public class Customer implements Serializable {

String name;

String address;

double phoneNumber;

int amount; // Added amount field

int points; // Added points field

public Customer(String name, String address, double phoneNumber) {

this.name = name;

16
22IT012

this.address = address;

this.phoneNumber = phoneNumber;

// Added input method

public void input(int amount) {

this.amount = amount;

// Added points_calculation method

public void points_calculation() {

// Your points calculation logic here

// For example:

this.points = amount * 10; // Just a sample calculation

@Override

public String toString() {

return "Name: " + name + ", Address: " + address + ", Phone Number: " + phoneNumber + ",
Points: " + points;

Customer Application using TCP:

//Server.java

import java.io.*;

import java.net.*;

public class Server {

17
22IT012

public static void main(String[] args) {

ServerSocket serverSocket = null;

try {

serverSocket = new ServerSocket(12345);

System.out.println("Server is running...");

while (true) {

// Accept incoming client connection

Socket clientSocket = serverSocket.accept();

System.out.println("Client connected: " +


clientSocket.getInetAddress().getHostAddress());

// Create object streams for sending and receiving objects

ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());

ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());

while (true) {

// Receive Customer object from the client

Customer customer = (Customer) ois.readObject();

System.out.println("Received from client: " + customer.toString());

// Process the received customer data (here, just echoing back)

String replyMessage = customer.toString();

oos.writeObject(replyMessage);

oos.flush();

} catch (IOException | ClassNotFoundException e) {

e.printStackTrace();

} finally {

18
22IT012

try {

if (serverSocket != null) serverSocket.close();

} catch (IOException e) {

e.printStackTrace();

//Client.java

import java.io.*;

import java.net.*;

public class Client {

public static void main(String[] args) {

Socket socket = null;

ObjectOutputStream oos = null;

ObjectInputStream ois = null;

try {

InetAddress serverAddress = InetAddress.getByName("localhost");

int serverPort = 12345;

// Connect to the server

socket = new Socket(serverAddress, serverPort);

System.out.println("Client is running...");

// Create object streams for sending and receiving objects

oos = new ObjectOutputStream(socket.getOutputStream());

19
22IT012

ois = new ObjectInputStream(socket.getInputStream());

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

while (true) {

System.out.println("Enter customer details:");

System.out.print("Name: ");

String name = reader.readLine();

System.out.print("Address: ");

String address = reader.readLine();

System.out.print("Phone Number: ");

double phoneNumber = Double.parseDouble(reader.readLine());

System.out.print("Enter the amount: ");

int amount = Integer.parseInt(reader.readLine());

// Create a Customer object with the provided details

Customer customer = new Customer(name, address, phoneNumber);

customer.input(amount);

// Send the Customer object to the server

oos.writeObject(customer);

oos.flush();

// Receive response from the server

String replyMessage = (String) ois.readObject();

System.out.println("Server says: " + replyMessage);

} catch (IOException | ClassNotFoundException e) {

20
22IT012

e.printStackTrace();

} finally {

try {

if (ois != null) ois.close();

if (oos != null) oos.close();

if (socket != null) socket.close();

} catch (IOException e) {

e.printStackTrace();

//Customer.java

import java.io.Serializable;

public class Customer implements Serializable {

String name;

String address;

double phoneNumber;

int amount; // Added amount field

int points; // Added points field

public Customer(String name, String address, double phoneNumber) {

this.name = name;

this.address = address;

this.phoneNumber = phoneNumber;

// Added input method

21
22IT012

public void input(int amount) {

this.amount = amount;

// Added points_calculation method

public void points_calculation() {

// points calculation logic here

this.points = amount * 10; // Just a sample calculation

@Override

public String toString() {

return "Name: " + name + ", Address: " + address + ", Phone Number: " + phoneNumber + ",
Points: " + points;

Output:

Chat application using UDP:

22
22IT012

Chat application using TCP

Customer application using UDP:

Customer application using TCP:

23
22IT012

Result:

The client- server using TCP and UDP protocols are executed successfully and the outputs
are recorded.

Rubric for Evaluation

Parameter Max Marks Marks Obtained

Complexity of the Application chosen 3

Uniqueness of the Code 10

24
22IT012

Use of Comment lines and standard coding 2


practices

Viva 5

Sub Total 20

Completion of experiment on time 3

Documentation 7

Sub Total 10

Signature of the faculty with Date

25

You might also like