0% found this document useful (0 votes)
30 views

Assignment-Soket Programming

Uploaded by

Dnyanda Nemade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Assignment-Soket Programming

Uploaded by

Dnyanda Nemade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Department of Computer Science and Applications

A.Y. 2023-2024.
Even Semester
==============================================================================
ASSSIGNMENT NUMBER -02
FYMCA- Div-A and Div-B
Topic- Socket Programming
Date: 26/2/2024 Submission Date: 4/03/2022
==============================================================================

Q.1.Write a program to implement client and server chat application, program is terminated when
client say "exit".
Ans:-
Client:-
import java.io.*;
import java.net.*;

class ChatClient {

static DataInputStream din, dis;


static DataOutputStream dos;

public static void main(String args[]) {


try {
Socket s = new Socket(InetAddress.getLocalHost(), 8080);

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


din = new DataInputStream(System.in);

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


String sendMssg;
while(true) {
System.out.print("Message to Server: ");
sendMssg = din.readLine();
dos.writeUTF(sendMssg);
if(sendMssg.equalsIgnoreCase("Exit")) {
s.close();
break;
}
System.out.println("SERVER: " + dis.readUTF());
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
Server:-
import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(8080);
while(true) {
Socket s = ss.accept();
MyThread thread = new MyThread(s);
thread.start();
}
}
catch (Exception e) {
System.out.println(e);
}
}
}

class MyThread extends Thread {


DataInputStream dis;
DataOutputStream dos;
BufferedReader serverReader;
Socket socket;

MyThread(Socket s) throws Exception {


socket = s;
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
serverReader = new BufferedReader(new InputStreamReader(System.in));
}

public void run() {


try {
String received, toSend;
while(true) {
received = dis.readUTF();
System.out.println("Client: " + received);
if (received.equalsIgnoreCase("Exit")) {
break; // Exit the loop if client says "Exit"
}
System.out.print("Message to client: ");
toSend = serverReader.readLine();
dos.writeUTF(toSend);
}
// Close the socket after the communication is finished
socket.close();
// Terminate the server
System.exit(0);
}
catch(Exception e) {
System.out.println(e);
}
}
}

Q.2.write a program to accept file name from client, server will validate where the file is present
or not if it is present, it will send the content to client side if the file is not present send the
message "file not present".
Ans:-
Client:-
import java.io.*;
import java.net.*;

class FileClient {
public static void main(String args[]) {
Socket s;
DataInputStream dis, din;
DataOutputStream dos;

try {
s = new Socket(InetAddress.getLocalHost(), 4000);

din = new DataInputStream(System.in);


dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());

while (true) {
System.out.print("Enter filename: ");
String filename = din.readLine();
dos.writeUTF(filename);

String response = dis.readUTF();


System.out.println(response);

if (response.equals("File not present")) {


break;
}
break;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Server:-
import java.net.*;
import java.io.*;

class FileServer {
public static void main(String args[]) throws Exception {
ServerSocket ss = new ServerSocket(4000);
Socket s;

while (true) {
s = ss.accept();
(new MyThread(s)).start();
}
}
}

class MyThread extends Thread {


DataInputStream dis;
DataOutputStream dos;
FileInputStream fin;

String fname;
String data = "";

public MyThread(Socket s) throws Exception {


dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
}

public void run() {


try {
fname = dis.readUTF();
File file = new File(fname);

if (file.exists()) {
fin = new FileInputStream(fname);

byte ch = (byte)fin.read();

while(ch!=-1) {
data = data + (char)ch;
ch = (byte)fin.read();
}

dos.writeUTF(new String(data));
} else {
dos.writeUTF("File not present");
}

System.exit(0);
} catch (Exception e) {
System.out.println(e);
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Q.3. write a program to take a number from client side and server will perform addition of all digit
and send it to client side.
Ans:-
Client:-
import java.io.*;
import java.net.*;

class SumClient {
public static void main(String args[]) throws UnknownHostException, IOException {
try {
Socket s = new Socket(InetAddress.getLocalHost(), 8080);
System.out.println("Connected with server");

// Taking a number input from the user


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a number: ");
int number = Integer.parseInt(br.readLine());

// Sending the number to the server


OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(number);

// Receiving the result from the server


InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
int result = dis.readInt();
System.out.println("Result from server: " + result);

// Closing resources
dos.close();
dis.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Server:-
import java.io.*;
import java.net.*;

class SumServer {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(8080);
System.out.println("Server Connected");

Socket s = ss.accept();
System.out.println("Client Connected");

// Receiving the number from the client


InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
int number = dis.readInt();

// Performing addition of all digits


int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}

// Sending the result back to the client


OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(sum);

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

Q.4.write a program to client server echo application.


Ans:-
Client:-
// To implemet the Echo-Client

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

class EchoClient
{
static Socket s;
static DataInputStream dis, din;
static DataOutputStream dos;

public static void main(String args[])


{
try
{
s = new Socket(InetAddress.getLocalHost(), 4000);
din = new DataInputStream(System.in);
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
while(true)
{
dos.writeUTF(din.readLine());
System.out.println("SERVER : " + dis.readUTF());
}
}

catch(Exception e)
{
System.out.println("EXCEPTION IN CLIENT : " + e);
}
}
}
Server:-
// To implement ECHO-SERVER

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

class EchoServer
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(4000);
Socket s;

while(true)
{
s = ss.accept();
(new MyThread(s)).start();
}
}
}

class MyThread extends Thread


{
DataInputStream dis;
DataOutputStream dos;
String str;

public MyThread(Socket s) throws Exception


{
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
}

public void run()


{
try
{
while(true)

{
str=dis.readUTF();
System.out.println("SERVER : " +str );
dos.writeUTF(str);

}
}

catch(Exception e)
{
System.out.println("EXCEPTION IN SERVER THREAD : " + e);
}

}
}
Q.5.write a program to take string from client and server will return
1. Number of vowels present in string.
2. Number of blank space present in String
3. Number of capitals alphabets in string
4. Number of digit present in string.
Ans:-
Client:-
import java.io.*;
import java.net.*;

class StringClient
{
public static void main(String args[]) throws UnknownHostException, IOException {
try {
Socket s = new Socket(InetAddress.getLocalHost(), 8080);
System.out.println("Connected with server");

// Taking input from the user


BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a string: ");
String userString = userInput.readLine();

// Sending the user input to the server


PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(userString);
// Receiving the counts from the server
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));

System.out.println("Results from server:");


System.out.println("Number of vowels: " + Integer.parseInt(br.readLine()));
System.out.println("Number of blank spaces: " + Integer.parseInt(br.readLine()));
System.out.println("Number of capital alphabets: " +
Integer.parseInt(br.readLine()));
System.out.println("Number of digits: " + Integer.parseInt(br.readLine()));

// Closing resources
br.close();
pw.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Server:-
import java.io.*;
import java.net.*;

class StringServer {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(8080);
System.out.println("Server is waiting for client...");
Socket s = ss.accept();
System.out.println("Client connected");

BufferedReader br = new BufferedReader(new


InputStreamReader(s.getInputStream()));
String clientMsg = br.readLine();

// Processing the string and counting different elements


int vowelsCount = 0;
int blankSpacesCount = 0;
int capitalAlphabetsCount = 0;
int digitsCount = 0;

for (char ch : clientMsg.toCharArray()) {


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelsCount++;
} else if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
vowelsCount++;
capitalAlphabetsCount++;
} else if (ch >= '0' && ch <= '9') {
digitsCount++;
} else if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\f') {
blankSpacesCount++;
} else if (ch >= 'A' && ch <= 'Z') {
capitalAlphabetsCount++;
}
}

// Sending the counts back to the client


PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(vowelsCount);
pw.println(blankSpacesCount);
pw.println(capitalAlphabetsCount);
pw.println(digitsCount);

// Closing resources
s.close();
ss.close();
br.close();
pw.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Q.6. Write a Client Server chat application to accept the query from Client (Update the
employee’s Salary by adding 10% Bonus on current Gross Salary Whose EMP designation = Sr.
Clerk) , After updating from server side send the reflected records to client side from server side.

Ans:-
Client:-
package Socket_Programming;

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

class QueryClient {
public static void main(String args[]) throws UnknownHostException, IOException {
try {
Socket s = new Socket(InetAddress.getLocalHost(), 8082);
System.out.println("Connected with Server");
DataInputStream dis = new DataInputStream(System.in);
System.out.print("Enter the query: ");
@SuppressWarnings("deprecation")
String query = dis.readLine();

OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(query);

// Receiving the result from the server


InputStream is = s.getInputStream();
DataInputStream din = new DataInputStream(is);
String result = din.readUTF();
System.out.println(result);

// Closing resources
din.close();
dos.close();
dis.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Server:-
package Socket_Programming;

import java.io.*;
import java.net.*;
import java.sql.*;
class QueryServer {
public static void main(String args[]) {
try {
System.out.println("Server connected");

ServerSocket ss = new ServerSocket(8082);


Socket s = ss.accept();
System.out.println("Client connected");

InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
String query = dis.readUTF();

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/College",
"root", "Wakt@420");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

// Get ResultSet metadata to dynamically fetch column names and count


ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();

// Storing the result in a StringBuilder


StringBuilder result = new StringBuilder();

// Append column names


for (int i = 1; i <= columnCount; i++) {
result.append(metaData.getColumnName(i)).append("\t");
}
result.append("\n");

// Append data
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
result.append(rs.getString(i)).append("\t");
}
result.append("\n");
}

// Sending the result back to the client


OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(result.toString());

// Closing resources
rs.close();
stmt.close();
con.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Q.7. Write Client Server application to take a String “AUCTION ” from client side and from server
side send how many total number of different word are possible using the word “AUCTION”.

Ans:-
Client:-
import java.io.*;
import java.net.*;
public class Q7client
{
static DataInputStream din,dis;
static DataOutputStream dos;
public static void main(String args[])
{
try
{
Socket s = new Socket(InetAddress.getLocalHost(),8030);

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


dis = new DataInputStream(System.in);

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


System.out.println("Enter a word: ");
dos.writeUTF(dis.readLine());
System.out.println(din.readUTF());
}
catch(Exception e)
{
System.out.println("EXCEPTION : " + e);
}
}
}
Server:-
import java.io.*;

import java.net.*;

public class Q7server

{
public static void main(String[] args)

try

ServerSocket ss = new ServerSocket(8030);

Socket s;

while (true)

s = ss.accept();

(new MyThread3(s)).start();

catch(Exception e){

System.out.println(e);

class MyThread3 extends Thread

DataInputStream dis;

DataOutputStream dos;
MyThread3(Socket s) throws Exception

try

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

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

catch(Exception e)

System.out.println(e);

public void run()

try

String inputString = dis.readUTF();

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

int totalWords = countUniqueWords(inputString);

dos.writeUTF("Total no. of unique words that are possible using the word '"+inputString+"'
are "+ totalWords);

System.exit(0);
}

catch(Exception e)

System.out.println(e);

public static int countUniqueWords(String word)

int totalPermutations = factorial(word.length());

return totalPermutations;

public static int factorial(int n)

if (n == 0 || n == 1)

return 1;

return n * factorial(n - 1);

}
Q.8. Write a client Server JDBC application to perform the following operations by passing
following queries for STUDENT DATABASE from client to server (GUI is to be design for Client
Side)

● Update student details.

● Delete students cancel admission.

● Retrieve student.

● List of all the student for MCA Sci program

● Avoid duplicate entry of StudentPRN. Display all students those who are scored 95% and
above marks in CET

Ans:-
Client:-
package Socket_Programming;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
public class Q8Client extends Frame implements ActionListener
{
static Socket s;
static DataInputStream dis,din;
static DataOutputStream dos;

Label l1,l2,l3,l4;
Button b1,b2,b3,b4,b5;
TextField tf1,tf2,tf3,tf4;
TextArea ta;
Panel p1,p2;
Connection cn;
PreparedStatement ps;
ResultSet rs;

public Q8Client()
{

setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
p1 = new Panel();
p1.setLayout(new GridLayout(4,2));

l1=new Label("Student PRN:");


l2=new Label("Student Name:");
l3=new Label("Course:");
l4=new Label("CET Marks:");

b1=new Button("View");
b2=new Button("Save");
b3 = new Button("Update");
b4 = new Button("ViewAll");
b5 = new Button("95%+");

tf1=new TextField(15);
tf2=new TextField(15);
tf3=new TextField(15);
tf4=new TextField(15);

ta = new TextArea(" ",10,40);


p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
p1.add(l3);
p1.add(tf3);
p1.add(l4);
p1.add(tf4);

p2 = new Panel();
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
p2.add(b5);

add("North",p1);
add("Center",p2);
add("South",ta);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
try
{
dos.writeUTF("exit");
} catch (IOException e)
{
e.printStackTrace();
}
System.exit(0);
}
});
try
{
Class.forName("com.mysql.cj.jdbc.Driver");

cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/College","root","Wakt@
420");
}
catch(Exception e)
{
System.out.println(e);
}
}

public void actionPerformed(ActionEvent ae)


{
try
{
if(ae.getSource()==b1)
{
String query ="select * from student1 where prn="+tf1.getText();
dos.writeUTF(query);
ta.append("\n"+dis.readUTF());
}
if(ae.getSource()==b2)
{
String query = "insert into student1
values("+tf1.getText()+",'"+tf2.getText()+"','"+tf3.getText()+"',"+tf4.getText()+")";
dos.writeUTF(query);
ta.append("\n"+dis.readUTF());
}
if(ae.getSource()==b3)
{
String query = "update student1 set course = "+tf3.getText()+" where
prn="+tf1.getText();
dos.writeUTF(query);
ta.append("\n"+dis.readUTF());
}
if(ae.getSource()==b4)
{
String query ="select * from student1";
dos.writeUTF(query);
ta.append("\n"+dis.readUTF());
}
if(ae.getSource()==b5)
{
String query ="select * from student1 where CET_Marks>95";
dos.writeUTF(query);
ta.append("\n"+dis.readUTF());
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args) throws UnknownHostException
{
Q8Client f = new Q8Client();
f.setSize(500,500);
f.setVisible(true);
try
{
s = new Socket(InetAddress.getLocalHost(),8085);

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


dos = new DataOutputStream(s.getOutputStream());
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Server:-
package Socket_Programming;

import java.io.*;

import java.net.*;

import java.sql.*;

public class Q8Server

public static void main(String args[])


{

try

Socket s;

ServerSocket ss = new ServerSocket(8085);

while(true)

s = ss.accept();

(new MyThread2(s)).start();

catch(Exception e)

System.out.println("EXCEPTION : " + e);

class MyThread2 extends Thread

DataInputStream dis,din;

DataOutputStream dos;

public MyThread2(Socket s) throws Exception

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

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

public void run()

while(true)

try

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con
=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","Wakt@420");

Statement st =con.createStatement();

String sql=dis.readUTF();

if(sql.equals("exit"))

System.exit(0);

if(sql.contains("select"))

ResultSet rs=st.executeQuery(sql);

ResultSetMetaData rm = rs.getMetaData();

int col=rm.getColumnCount();

StringBuilder b = new StringBuilder();

b.append("PRN\tName\tCourse\t\tCET Marks\n");
while(rs.next())

for(int i=1; i<=col; i++)

String data = rs.getString(i);

b.append(data +"\t");

b.append("\n");

rs.close();

dos.writeUTF(b.toString());

else

StringBuilder b = new StringBuilder();

int up = st.executeUpdate(sql);

b.append(up+"Records updated!");

System.out.println(b);

dos.writeUTF(b.toString());

st.close();

con.close();

}
catch (Exception e)

System.out.println(e);

Q.9. Write a short note on

1. InetAddress.getLocalHost()

Ans:-

InetAddress.getLocalHost() is a method in Java used to retrieve the IP address of the local host
machine. It returns an instance of InetAddress representing the local host. This method is
commonly used in networking applications to obtain information about the local system,
particularly its IP address, which can be crucial for establishing connections or determining
network configurations.

It's important to note that while this method typically returns the IP address of the local machine,
there are cases where it might not behave as expected, such as in virtualized or containerized
environments where the concept of "localhost" might be different.

Here's a simple example demonstrating the usage of InetAddress.getLocalHost():

java

import java.net.*;
public class LocalHostExample {

public static void main(String[] args) {

try {

InetAddress localHost = InetAddress.getLocalHost();

System.out.println("Local Host IP Address: " + localHost.getHostAddress());

System.out.println("Local Host Name: " + localHost.getHostName());

} catch (UnknownHostException e) {

System.err.println("Error: " + e.getMessage());

This code snippet retrieves the IP address and hostname of the local machine and prints them
out. However, it's important to handle the UnknownHostException which may occur if the local
host is not recognized or if there are network configuration issues.

2. UserDataGrram Class

Ans:-

The UserDataGram class is not a standard class in Java. It seems there might be a typo or
misunderstanding. However, if you meant DatagramPacket class, I can provide information on
that.
DatagramPacket is a class in Java used for implementing the User Datagram Protocol (UDP)
communication. UDP is a connectionless protocol that operates on the transport layer of the
Internet Protocol (IP) suite. Unlike TCP, UDP does not establish a connection before
transmitting data and does not guarantee delivery or order of packets.

DatagramPacket represents a packet of data to be sent or received over a network using UDP. It
contains two main pieces of information: the data itself and the destination or source address
information. It's commonly used in network programming for sending and receiving small
amounts of data where speed and low overhead are prioritized over reliability.

Here's a brief overview of how DatagramPacket works:

- To send data: You create a DatagramPacket object containing the data to be sent along with
the destination address (IP address and port number). This packet is then sent using a
DatagramSocket.

- To receive data: You create a DatagramPacket object with an empty buffer to receive
incoming data. This packet is passed to a DatagramSocket which listens for incoming packets.
When a packet arrives, its data is copied into the buffer of the DatagramPacket, and you can
retrieve the data from there.

Here's a simple example of sending and receiving data using DatagramPacket:

java

import java.net.*;
public class DatagramExample {

public static void main(String[] args) {

try {

DatagramSocket socket = new DatagramSocket(); // Create socket for sending

byte[] sendData = "Hello, World!".getBytes();

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

int port = 12345;

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,


address, port);

socket.send(sendPacket); // Send the packet

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

socket.receive(receivePacket); // Receive the packet

String receivedMessage = new String(receivePacket.getData(), 0,


receivePacket.getLength());

System.out.println("Received message: " + receivedMessage);

socket.close(); // Close the socket

} catch (Exception e) {

e.printStackTrace();

}
}

In this example, we create a DatagramSocket for sending and receiving data. We then create
DatagramPacket objects for sending and receiving data, specifying the data buffer, destination
address, and port number. Finally, we send and receive data using the send() and receive()
methods of the DatagramSocket.

You might also like