Assignment-Soket Programming
Assignment-Soket Programming
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 {
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);
while (true) {
System.out.print("Enter filename: ");
String filename = din.readLine();
dos.writeUTF(filename);
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();
}
}
}
String fname;
String data = "";
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");
// 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");
// Closing resources
dos.close();
dis.close();
s.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.io.*;
import java.net.*;
class EchoClient
{
static Socket s;
static DataInputStream dis, din;
static DataOutputStream dos;
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();
}
}
}
{
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");
// 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");
// 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);
// 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");
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);
// Append data
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
result.append(rs.getString(i)).append("\t");
}
result.append("\n");
}
// 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);
import java.net.*;
{
public static void main(String[] args)
try
Socket s;
while (true)
s = ss.accept();
(new MyThread3(s)).start();
catch(Exception e){
System.out.println(e);
DataInputStream dis;
DataOutputStream dos;
MyThread3(Socket s) throws Exception
try
catch(Exception e)
System.out.println(e);
try
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);
return totalPermutations;
if (n == 0 || n == 1)
return 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)
● Retrieve student.
● 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));
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);
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);
}
}
import java.io.*;
import java.net.*;
import java.sql.*;
try
Socket s;
while(true)
s = ss.accept();
(new MyThread2(s)).start();
catch(Exception e)
DataInputStream dis,din;
DataOutputStream dos;
{
dis= new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
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();
b.append("PRN\tName\tCourse\t\tCET Marks\n");
while(rs.next())
b.append(data +"\t");
b.append("\n");
rs.close();
dos.writeUTF(b.toString());
else
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);
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.
java
import java.net.*;
public class LocalHostExample {
try {
} catch (UnknownHostException e) {
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.
- 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.
java
import java.net.*;
public class DatagramExample {
try {
} 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.