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

Program No PDF

The document describes a Java program that implements a calculator using Java applets. It imports necessary packages and defines a CALCULATOR class that extends JApplet and implements ActionListener. The class initializes the GUI components like text field and buttons, adds action listeners, and defines logic for performing calculations when buttons are clicked. On running the applet, it displays a basic calculator interface that can perform addition, subtraction, multiplication and division operations.

Uploaded by

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

Program No PDF

The document describes a Java program that implements a calculator using Java applets. It imports necessary packages and defines a CALCULATOR class that extends JApplet and implements ActionListener. The class initializes the GUI components like text field and buttons, adds action listeners, and defines logic for performing calculations when buttons are clicked. On running the applet, it displays a basic calculator interface that can perform addition, subtraction, multiplication and division operations.

Uploaded by

Sharon Joseph
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Program No: 1

CALCULATOR USING JAVA APPLET


Aim: Write a Java program to implement Calculator using Java Applet.
PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

//<applet code = "CALCULATOR.class" width = 260 height = 310></applet>

public class CALCULATOR extends JApplet implements ActionListener


{
JTextField t1;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
JButton add,sub,mul,div, eql, dot;
String msg="",tmp;
int a, b;
public void init()
{
setLayout(null);
t1=new JTextField(20);
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");

1
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
add=new JButton("+");
sub=new JButton("-");
div=new JButton("/");
mul=new JButton("*");
dot=new JButton(".");
eql=new JButton("=");

add(t1);
add(b7);
add(b8);
add(b9);
add(div);

add(b4);
add(b5);
add(b6);
add(mul);

add(b1);
add(b2);
add(b3);
add(sub);

add(dot);

2
add(b0);
add(eql);
add(add);

t1.setBounds(30,30,200,40);
b7.setBounds(30,80,44,44);
b8.setBounds(82,80,44,44);
b9.setBounds(134,80,44,44);
b4.setBounds(30,132,44,44);
b5.setBounds(82,132,44,44);
b6.setBounds(134,132,44,44);
b1.setBounds(30,184,44,44);
b2.setBounds(82,184,44,44);
b3.setBounds(134,184,44,44);
dot.setBounds(30,236,44,44);
b0.setBounds(82,236,44,44);
eql.setBounds(134,236,44,44);
add.setBounds(186,236,44,44);
sub.setBounds(186,184,44,44);
mul.setBounds(186,132,44,44);
div.setBounds(186,80,44,44);

b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

3
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
//b0.addActionListener(this);
//b0.addActionListener(this);
div.addActionListener(this);
mul.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
eql.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if (str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/"))
{
String str1 = t1.getText();
tmp=str;
a = Integer.parseInt(str1);
msg="";
}
else if(str.equals("="))
{
String str2 = t1.getText();
b = Integer.parseInt(str2);
int sum=0;
if(tmp=="+")

4
sum=a+b;
else if(tmp=="-")
sum=a-b;
else if(tmp=="*")
sum=a*b;
else if(tmp=="/")
sum=a/b;
String str1=String.valueOf(sum);
t1.setText(""+str1);
msg="";
}
else
{
//String ae.getActionCommand();
//str += ae.getActionCommand();
msg+=str;
t1.setText(""+msg);
}
}
public void paint(Graphics g)
{
g.setColor(Color.cyan);
g.fillRect(20,20,220,270);
}
}

5
OUTPUT

6
Program No: 2

THREAD SYNCHRONIZATION
Aim: Write a Java program to implement Thread Synchronization.
PROGRAM:
class Square
{
synchronized public void draw(char ch)
{
try
{
for (int i=0;i<6 ;i++ ) {
for (int j=0;j<i ;j++ ) {
System.out.print(ch);
}

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

}
}
}
class Athread extends Thread
{
Square sq;
Athread(Square sq)

7
{
this.sq=sq;
}
public void run()
{
sq.draw('*');

}
class Bthread extends Thread
{
Square sq;
Bthread(Square sq)
{
this.sq=sq;
}
public void run()
{
sq.draw('v');

}
class Synchronization2
{
public static void main(String[] args) {
Square sqr=new Square();

8
Athread a=new Athread(sqr);
Bthread b=new Bthread(sqr);
a.start();
b.start();
}
}

OUTPUT

9
Program No: 3

THREAD USING RUNNABLE INTERFACE


Aim: Write a Java program to Thread using Runnable interface.
PROGRAM:
class RunTh implements Runnable
{
public void run()
{
for (int i=0;i<6 ;i++ ) {
for (int j=0;j<i ;j++ ) {
System.out.print("*");
}

System.out.println();
}
}
}
class RunTh1 implements Runnable
{
public void run()
{
for (int i=0;i<6 ;i++ ) {
for (int j=0;j<i ;j++ ) {
System.out.print("/");
}

System.out.println();
}

10
}
}
class RunTh2 implements Runnable
{
public void run()
{
for (int i=0;i<6 ;i++ ) {
for (int j=0;j<i ;j++ ) {
System.out.print("^");
}

System.out.println();
}
}
}
class Sychronization
{
public static void main(String []at)

{
RunTh th1 = new RunTh();
RunTh1 th2 = new RunTh1();
RunTh2 th3 = new RunTh2();
Thread thh1 = new Thread(th1);
Thread thh2 = new Thread(th2);
Thread thh3 = new Thread(th3);
thh1.start();
thh2.start();

11
thh3.start();
System.out.println(thh1.toString()+ " "+thh2.toString()+" "+thh3.toString());
System.out.println(thh1.getThreadGroup()+ " "+thh2.getThreadGroup()+"
"+thh3.getThreadGroup());
}
}
OUTPUT

12
Program No: 4

THREAD USING THREAD CLASS


Aim: Write a Java program to implements Thread using Thread class.
PROGRAM:
class Square
{
synchronized public void draw(char ch)
{
try
{
for (int i=0;i<6 ;i++ ) {
for (int j=0;j<i ;j++ ) {
System.out.print(ch);
}

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

}
}
}
class Athread extends Thread
{
Square sq;
Athread(Square sq)

13
{
this.sq=sq;
}
public void run()
{
sq.draw('*');

}
class Bthread extends Thread
{
Square sq;
Bthread(Square sq)
{
this.sq=sq;
}
public void run()
{
sq.draw('v');

}
class Synchronization2
{
public static void main(String[] args) {
Square sqr=new Square();

14
Athread a=new Athread(sqr);
Bthread b=new Bthread(sqr);
a.start();
b.start();
}
}
OUTPUT

15
Program No: 5

BYTE AND CHARACTER STREAM CLASS


Aim:
Write a Java program to implement Byte and Character stream class.
PROGRAM:
import java.io.*;
import java.util.*;
class ByteChar
{
public static void main(String args[])
{
try{
FileOutputStream fos=new FileOutputStream("abc.txt");
String str="";
System.out.println("Byte IO");
System.out.println("Enter your favorite book ");
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
byte by[] = str.getBytes();
fos.write(by);
fos.close();
FileInputStream fis=new FileInputStream("abc.txt");
FileOutputStream fos1=new FileOutputStream("abcd.txt");
int ch=0;
System.out.println("Content of file");
while((ch=fis.read())!=-1)
{
System.out.print((char)ch);

16
fos1.write(ch);
}
fis.close();
fos1.close();

}
catch(Exception e)
{
System.out.println(e.getMessage());
}
try
{
System.out.println("\n");
System.out.println("Character IO");
Writer os=new FileWriter("myfile2.txt");
char b[]={'S','H','A','R','O','N',' '};
os.write(b);
for(int i=76;i<82;i++)
{
os.write(i);
}
os.flush();
os.close();
Reader is=new FileReader("myfile2.txt");
int ch;
while((ch=is.read())!=-1)
{
System.out.printf("%c",ch);

17
}
is.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}

}}

OUTPUT

18
Program No: 6

FILTER IO STREAMS
Aim:
Write a Java program to implement Filter IO Streams.
PROGRAM:
import java.io.*;
class FilterIO
{
public static void main(String[] args) {
try{
FileInputStream fs = new FileInputStream("file.txt");
FilterInputStream fis = new BufferedInputStream(fs);
FileOutputStream fo = new FileOutputStream("newfile.txt");
FilterOutputStream fos = new FilterOutputStream(fo);
int ch=0;
while((ch=fis.read())!=-1)
{
System.out.print((char)ch);
fos.write(ch);
fis.skip(1);
}
fs.close();
fis.close();
fo.close();
fos.close();
}
catch(Exception e)
{

19
System.out.println(e);
}
}
}
OUTPUT

NB:-
File “file.txt” will contain “The Journey from Platform NINE AND THREE QUARTERS”, when
executing the program, it will filter the data to “TeJunyfo ltomNN N HE URES”. And the output
is entered to a new file “newfile.txt” and also displayed on the console.

20
Program No: 7

Piped IO STREAMS
Aim: Write a Java program to implement Piped IO Streams.
PROGRAM:
import java.io.*;
class WriteTh extends Thread
{
PipedOutputStream pos = new PipedOutputStream();
public WriteTh(PipedOutputStream ob)
{
pos=ob;
}
public void run()
{
try
{
for(int i=0;i<5;i++)
{
pos.write(i);
}
}
catch(Exception ex)
{
System.out.print(ex.getMessage());
}
}
}
class ReadTh extends Thread

21
{
PipedInputStream pis = new PipedInputStream();
public ReadTh(PipedInputStream ob)
{
pis=ob;
}
public void run()
{
try
{
int ch;
while ((ch = pis.read())!=-1)
System.out.println("First "+ch);
}
catch(Exception ex)
{
System.out.print(ex.getMessage());
}
}
}
class ReadTh1 extends Thread
{
PipedInputStream pis = new PipedInputStream();
public ReadTh1(PipedInputStream ob)
{
pis=ob;
}
public void run()

22
{
try
{
int ch;
while ((ch=pis.read())!=-1)
{
System.out.println("Second " +ch);
}
}
catch(Exception ex)
{
System.out.print(ex.getMessage());
}
}
}
class MyPipeEx
{
public static void main(String[] args)
{
try
{
PipedOutputStream po = new PipedOutputStream();
PipedInputStream pi = new PipedInputStream(po);
WriteTh th1=new WriteTh(po);
ReadTh th2 = new ReadTh(pi);
ReadTh1 th3 = new ReadTh1(pi);
th1.start();
th2.start();

23
th3.start();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
OUTPUT

24
Program No: 8

SERIALIZATION
Aim: Write a Java program to implement Serialization.
PROGRAM:
import java.io.*;
import java.util.*;
class stuClass implements Serializable
{
String stname;
int m1,m2;
int avg=0;
public void readData()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter your name:");
stname=sc.nextLine();
System.out.println("Enter your marks of 2 subjects out of 50");
m1=sc.nextInt();
m2=sc.nextInt();
}
public void printData()
{
System.out.println("+------------------------+");
System.out.println("Name:"+stname+" ");
System.out.println("Mark1: "+m1+" ");
System.out.println("Mark2: "+m2+" ");
}
public void printAverage()

25
{
avg=(m1+m2)/2;
System.out.println("Average :"+avg+" ");
}
public void printResult()
{
System.out.println("Result : ");
if(avg>=40)
System.out.println("Distinction !");
else if(avg>=30&&avg<40)
System.out.println("First Class !");
else if(avg>=24&&avg<30)
System.out.println("Second class !");
else
System.out.println("Failed !");
}
}
class StudentDetails
{
public static void main(String args[])
{
try
{
FileOutputStream fis=new FileOutputStream("Student.dat");
ObjectOutputStream obs=new ObjectOutputStream(fis);
stuClass s=new stuClass();
for(int i=0;i<2;++i)
{

26
s.readData();
obs.writeObject(s);
obs.reset();
}
obs.close();
FileInputStream fin=new FileInputStream("Student.dat");
ObjectInputStream is=new ObjectInputStream(fin);
stuClass iob=new stuClass();
System.out.println("**STUDENTS MARK LIST**");
for(int i=0;i<2;i++)
{
iob=(stuClass)is.readObject();
iob.printData();
iob.printAverage();
iob.printResult();
}
is.close();
}
catch(Exception e)
{
System.out.print("Exception");
}

}
}

27
OUTPUT

28
Program No: 9

WINDOWS EXPLORER
Aim: Write a Java program to demonstrate Windows Explorer.
PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.filechooser.*;
import java.io.File;
class FileManager implements TreeSelectionListener, ActionListener
{
String pathToFileOnDisk = "logo.png";
JFrame jfr = new JFrame("File Explorer");
JTree jt = new JTree();
Container ctr = new Container();
JTextField jtf = new JTextField("");

29
JMenuBar jmr = new JMenuBar();
JMenu jmu = new JMenu("File");
JMenuItem jmi1 = new JMenuItem("Close");
JMenuItem jmi2 = new JMenuItem("Open");
DefaultListModel <String> listModel = new DefaultListModel<>();
JList <String> lst = new JList<>(listModel);
JTree tree;
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Types of Cuisines");
DefaultMutableTreeNode root4 = new DefaultMutableTreeNode("Mexican");
DefaultMutableTreeNode top14 = new DefaultMutableTreeNode("Horchata");
DefaultMutableTreeNode top15 = new DefaultMutableTreeNode("Chicken Tamales");
DefaultMutableTreeNode root5 = new DefaultMutableTreeNode("Italian");
DefaultMutableTreeNode top51 = new DefaultMutableTreeNode("Spaghetti all'Amatriciana");
DefaultMutableTreeNode top52 = new DefaultMutableTreeNode("Lasagne Alla Bolognese
Saporite");
DefaultMutableTreeNode root1 = new DefaultMutableTreeNode("Indian");
DefaultMutableTreeNode top11 = new DefaultMutableTreeNode("Andra");
DefaultMutableTreeNode tchild11 = new DefaultMutableTreeNode("Atukulu");
DefaultMutableTreeNode tchild12 = new DefaultMutableTreeNode("Sakinalu ");
DefaultMutableTreeNode top12 = new DefaultMutableTreeNode("Kerala");
DefaultMutableTreeNode tchild121 = new DefaultMutableTreeNode("Kozhikodan Halwa");
DefaultMutableTreeNode tchild122 = new DefaultMutableTreeNode("Thalassery Biriyani");
DefaultMutableTreeNode root2 = new DefaultMutableTreeNode("Thai Food");
DefaultMutableTreeNode root3 = new DefaultMutableTreeNode("Chinese");
DefaultMutableTreeNode top31 = new DefaultMutableTreeNode("Chow mein");
DefaultMutableTreeNode top32 = new DefaultMutableTreeNode("Zhajiangmian");
DefaultMutableTreeNode top1 = new DefaultMutableTreeNode("Japanese");
DefaultMutableTreeNode tpchild11 = new DefaultMutableTreeNode("Rice dishes ");
DefaultMutableTreeNode tpchild112 = new DefaultMutableTreeNode("Rice");
30
DefaultMutableTreeNode tpchild113 = new DefaultMutableTreeNode("Hayashi rice");
DefaultMutableTreeNode tpchild114 = new DefaultMutableTreeNode("Kamameshi");
DefaultMutableTreeNode tpchild12 = new DefaultMutableTreeNode("Drivers");
DefaultMutableTreeNode tchild13 = new DefaultMutableTreeNode("Other Staples ");
DefaultMutableTreeNode tchild131 = new DefaultMutableTreeNode("Noodles");
DefaultMutableTreeNode tchild1311 = new DefaultMutableTreeNode("Ramen");
DefaultMutableTreeNode tchild1312 = new DefaultMutableTreeNode("Hiyashi chūka ");
DefaultMutableTreeNode tchild132 = new DefaultMutableTreeNode("Bread");
DefaultMutableTreeNode tchild133 = new DefaultMutableTreeNode("Deep-fried dishes");
DefaultMutableTreeNode tchild1331 = new DefaultMutableTreeNode("Agemono");
DefaultMutableTreeNode tchild14 = new DefaultMutableTreeNode("Kushikatsu ");
DefaultMutableTreeNode tchild15 = new DefaultMutableTreeNode("Satsuma-age");
DefaultMutableTreeNode tchild16 = new DefaultMutableTreeNode("Tempura");
DefaultMutableTreeNode tchild17 = new DefaultMutableTreeNode("Kakiage");
DefaultMutableTreeNode top2 = new DefaultMutableTreeNode("Moroccan");
DefaultMutableTreeNode tchild21 = new DefaultMutableTreeNode("Salads");
DefaultMutableTreeNode tchild22 = new DefaultMutableTreeNode("Main Dishes");
DefaultMutableTreeNode tchild221 = new DefaultMutableTreeNode("Baghrir");
DefaultMutableTreeNode tchild222 = new DefaultMutableTreeNode("Briouat");
DefaultMutableTreeNode tchild2221 = new DefaultMutableTreeNode("Brochette Boulfaf");
DefaultMutableTreeNode tchild2222 = new DefaultMutableTreeNode("Couscous");
DefaultMutableTreeNode top3 = new DefaultMutableTreeNode("Mediterranean Cuisine");
FileManager()
{
try
{
ImageIcon img = new ImageIcon(pathToFileOnDisk);
jfr.setIconImage(img.getImage());

31
jfr.setLayout(null);
jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfr.setSize(700,600);
ctr = jfr.getContentPane();
/* Add menu bar */
jmu.add(jmi1);
jmu.add(jmi2);
jmr.add(jmu);
jmr.setBounds(10, 10, 600, 30);
ctr.add(jmr);
jtf.setBounds(50, 40, 600, 20);
ctr.add(jtf);
root.add(root4);root.add(root5);root.add(root1); root.add(root2); root.add(root3);
root.add(top1); root.add(top2);root.add(top3);
root5.add(top51);root5.add(top52);
root4.add(top14);root4.add(top15);
root3.add(top31);root3.add(top32);
root1.add(top11); root1.add(top12);
top11.add(tchild11);top11.add(tchild12);
top12.add(tchild121);top12.add(tchild122);
top1.add(tpchild11);
tpchild11.add(tpchild112);
tpchild112.add(tpchild113);tpchild112.add(tpchild114);
top1.add(tchild13);
tchild13.add(tchild131);
tchild131.add(tchild1311);tchild131.add(tchild1312);
tchild13.add(tchild132);
tchild13.add(tchild133);

32
tchild133.add(tchild1331);
top1.add(tchild14);top1.add(tchild15);
top1.add(tchild16);top1.add(tchild17);
top2.add(tchild21);
top2.add(tchild22);
tchild22.add(tchild221);tchild22.add(tchild222);
tchild222.add(tchild2221);tchild222.add(tchild2222);
tree = new JTree(root);
tree.setBounds(10, 150, 200, 300);
ctr.add(tree);
tree.addTreeSelectionListener(this);
lst.setBounds(350, 150, 300, 300);
ctr.add(lst);
jmi1.addActionListener(this);
jmi2.addActionListener(this);
jfr.setVisible(true);
}
catch(Exception ae)
{
System.out.println(ae.getMessage());
}
}
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
if(cmd=="Close")
{
jfr.dispose();

33
}
if(cmd=="Open")
{
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
JOptionPane.showMessageDialog(jfr, "Command: " + file.getPath());
}
}
}
public void valueChanged(TreeSelectionEvent e)
{
try{
DefaultMutableTreeNode sel =
(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String str=e.getNewLeadSelectionPath().toString();
String str1=str.replace(',','\\');
str1=str1.replace('[',' ');
str1=str1.replace(']',' ');
jtf.setText(str1);
listModel.clear();
//System.out.println(sel.getChildCount());
//Enumeration <DefaultMutableTreeNode> children = sel.children();
Enumeration children = sel.children();
DefaultMutableTreeNode child = null;
//listModel.addElement(sel.toString());
while (children.hasMoreElements() )
34
{
child = (DefaultMutableTreeNode) children.nextElement();
listModel.addElement(child.toString());
}
//listModel.addElement(obj.toString());
}
catch(Exception ae)
{
System.out.println(ae.getMessage());
}
}
public static void main(String []argv)
{
try{
FileManager myExp = new FileManager();
}
catch(Exception ae)
{
System.out.println(ae.getMessage());
}
}
}

OUTPUT

35
Program No: 10

36
InetAddress CLASS
Aim: Write a program to demonstrate the use of various functions in InetAddress class.
PROGRAM:
import java.io.*;
import java.net.*;
import java.net.InetAddress;
public class InetDemo
{
public static void main(String[] args)
{
try
{
InetAddress ip=InetAddress.getByName("www.google.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
//List all IP addresses associate with a hostname/domain
InetAddress[] google = InetAddress.getAllByName("google.com");

for (InetAddress addr : google) {


System.out.println(addr.getHostAddress());
}
System.out.println("Local Address : " + ip.isAnyLocalAddress());
System.out.println("Link Local Address : " + ip.isLinkLocalAddress());
System.out.println("Loopback Address : " + ip.isLoopbackAddress());
System.out.println("Multicast Global Address : " + ip.isMCGlobal());
System.out.println("Multicast Link Local Address : " + ip.isMCLinkLocal());
System.out.println("Multicast Node Local : " + ip.isMCNodeLocal());
System.out.println("MulticastOrganisation Scope : " + ip.isMCOrgLocal());

37
System.out.println("Site Local Address: " + ip.isMCSiteLocal());
System.out.println("Multicast Address : " + ip.isMulticastAddress());
System.out.println("Site Local Address : " + ip.isSiteLocalAddress());
System.out.println("hashCode : " + ip.hashCode());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT

Program No: 11

38
UDP COMMUNICATION
Aim: Write a program to demonstrate the UDP Communication.
PROGRAM:
UDPServer.java
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
try
{
DatagramSocket serverSocket = new DatagramSocket(9999);
byte[] receiveData = new byte[321];
byte[] sendData = new byte[321];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);

39
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

UDPClient.java
import java.net.*;
import java.util.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
try
{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[321];
byte[] receiveData = new byte[321];
System.out.println("Enter a message :");
Scanner sc=new Scanner(System.in);
String sentence = sc.nextLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
9999);
40
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER : " );
System.out.println("Capitalized Sentence " + modifiedSentence);
clientSocket.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

OUTPUT

Program No: 12

TCP COMMUNICATION

41
Aim: Write a program to demonstrate the use of TCP Communication.
PROGRAM:
CServer.java
import java.io.IOException;
import java.io.*;
import java.nio.*;
import java.util.stream.IntStream;
import java.util.*;
import java.net.*;
class CServer
{
public static void main(String []ar) throws Exception
{
try
{
System.out.println("Server - waiting for client request");
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept();
System.out.println("Client request - received");
System.out.println(s);
DataInputStream br = new DataInputStream(s.getInputStream());
String str = br.readUTF();
char a=str.charAt(0);
int i,j,k;
for(i=1; i<=5; i++)
{
for(j=4; j>=i; j--)
{

42
System.out.print(" ");
}
for(k=1; k<=(2*i-1); k++)
{
System.out.print(a);
}
System.out.println("");
}
}

catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
Cclient.java
import java.io.IOException;
import java.io.*;
import java.nio.*;
import java.util.stream.IntStream;
import java.util.*;
import java.net.*;
class Cclient
{
public static void main(String []ar) throws Exception
{

43
try
{
String host = "localhost";
int port = 9999;
System.out.println("Enter a character to make star pattern:");
Scanner sc=new Scanner(System.in);
char a=sc.next().charAt(0);
String str=String.valueOf(a);
Socket s = new Socket(host, port);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
os.writeUTF(str);
os.flush();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}}

OUTPUT

44
Program No: 13

45
HTTP COMMUNICATION
Aim: Write a program to demonstrate the HTTP Communication.
PROGRAM:
import java.io.*;
import java.net.*;
import javax.net.*;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import java.security.*;
class CTestProtocol
{
static URL ur;
static boolean supported = false;
static public void testProtocol(String str)
{
try{
ur = new URL(str);
System.out.println(str +" "+ ur.getProtocol()+" "+ "-Supported");
supported = true;
}
catch(Exception ex)
{
System.out.println("Exception : "+ex.getMessage()+str +" - Not supported");
}
}
public static void main(String []ar) throws Exception

46
{
try
{ testProtocol("https://stackoverflow.com");
System.out.println("Host name: "+ur.getHost());
System.out.println("Protocol name: "+ur.getProtocol());
System.out.println("Protocol port: "+ur.getPort());
System.out.println("Protocol default port: "+ur.getDefaultPort());
System.out.println("Get reference: "+ur.getRef());
System.out.println("Query string: "+ur.getQuery());
System.out.println("User info: "+ur.getUserInfo());
System.out.println("Authority info: "+ur.getAuthority());
InputStream is = ur.openStream();
int ch;
while ((ch = is.read()) != -1)
{
System.out.write(ch);
}
is.close();
}
catch(Exception ex)
{
System.out.println("Exception : "+ex.getMessage());
}
}}

OUTPUT

47
NB:- The output cannot be included completely in the screenshot so, only relevant information is
included.

Program No: 14

48
URL COMMUNICATION
Aim: Write a program to demonstrate the use of various function in URL class.
PROGRAM:
import java.net.*;
import java.io.*;

public class URLDemo {

public static void main(String [] args) {


try {
URL url = new URL("https://www.tutorialspoint.com/java");

System.out.println("URL is " + url.toString());


System.out.println("protocol is " + url.getProtocol());
System.out.println("authority is " + url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is " + url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
System.out.println("class: "+url.getClass().getName());
}
catch (IOException e)
{
e.printStackTrace();
OUTPUT

49
Program No: 15

50
CHAT PROGRAM USING SOCKETS
Aim: Write a program to implement chat program using sockets.
PROGRAM:
ChatServer.java
import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;
// Server class
public class ChatServer
{
public static void main(String[] args) throws IOException
{

// server is listening on port 5056


ServerSocket ss = new ServerSocket(5056);
// running infinite loop for getting
// client request
while (true)
{
Socket s = null;
try
{
// socket object to receive incoming client requests
s = ss.accept();
System.out.println("A new client is connected : " + s);
// obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());

51
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assigning new thread for this client");
// create a new thread object
Thread t = new ClientHandler(s, dis, dos);
// Invoking the start() method
t.start();
}
catch (Exception e){
s.close();
e.printStackTrace();
}
}
}
}
// ClientHandler class
class ClientHandler extends Thread
{
DateFormat fordate = new SimpleDateFormat("yyyy/MM/dd");
DateFormat fortime = new SimpleDateFormat("hh:mm:ss");
final DataInputStream dis;
final DataOutputStream dos;
final Socket s;
// Constructor
public ClientHandler(Socket s, DataInputStream dis, DataOutputStream dos)
{
this.s = s;
this.dis = dis;
this.dos = dos;

52
}
@Override
public void run()
{
String received;
String toreturn;
while (true)
{
try {
// Ask user what he wants
dos.writeUTF("What do you want?[Date | Time]..\n"+
"Type Exit to terminate connection.");
// receive the answer from client
received = dis.readUTF();
if(received.equals("Exit"))
{
System.out.println("Client " + this.s + " sends exit...");
System.out.println("Closing this connection.");
this.s.close();
System.out.println("Connection closed");
break;
}
// creating Date object
Date date = new Date();
// write on output stream based on the
// answer from the client
switch (received) {
case "Date" :

53
toreturn = fordate.format(date);
dos.writeUTF(toreturn);
break;
case "Time" :
toreturn = fortime.format(date);
dos.writeUTF(toreturn);
break;
case "Msg" :
Scanner scanner=new Scanner(System.in);
toreturn=scanner.nextLine();
dos.writeUTF(toreturn);
break;
default:
dos.writeUTF("Invalid input");
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
try
{
// closing resources
this.dis.close();
this.dos.close();
}catch(IOException e){
e.printStackTrace();
}

54
}
}
ChatClient.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
// Client class
public class ChatClient
{
public static void main(String[] args) throws IOException
{
try
{
Scanner scn = new Scanner(System.in);
// getting localhost ip
InetAddress ip = InetAddress.getByName("localhost");
// establish the connection with server port 5056
Socket s = new Socket(ip, 5056);
// obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// the following loop performs the exchange of
// information between client and client handler
while (true)
{
System.out.println(dis.readUTF());
String tosend = scn.nextLine();
dos.writeUTF(tosend);

55
// If client sends exit,close this connection
// and then break from the while loop
if(tosend.equals("Exit"))
{
System.out.println("Closing this connection : " + s);
s.close();
System.out.println("Connection closed");
break;
}
// printing date or time as requested by client
String received = dis.readUTF();
System.out.println(received);
}
// closing resources
scn.close();
dis.close();
dos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

OUTPUT

56
57

You might also like