0% found this document useful (0 votes)
71 views41 pages

OOP Networking

The document describes algorithms for Java programs implementing networking, RMI, AWT, and Swing concepts. For networking, it explains creating server and client sockets to allow communication between the two. For RMI, it outlines creating an interface and class to perform a remote method call. And for AWT and Swing, it details creating GUI elements like buttons, labels and text fields to handle user input and display output.

Uploaded by

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

OOP Networking

The document describes algorithms for Java programs implementing networking, RMI, AWT, and Swing concepts. For networking, it explains creating server and client sockets to allow communication between the two. For RMI, it outlines creating an interface and class to perform a remote method call. And for AWT and Swing, it details creating GUI elements like buttons, labels and text fields to handle user input and display output.

Uploaded by

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

EX.

NO:9 NETWORKING

Aim:
To write a java Program to implement Networking concepts.

Algorithm:
Server:
1. Create a provider class in that class creating server
socket.
Provider Socket =new Server Socket(2004,10);
2. Wait for connection.
3. Get input and output stream.
4. The two part communicate via input and output streams.
5. Error in try block catch the exception and display.
6. Finally closing the connection.
7. In main() method create object for class provider and call
function.

Server.run();
Client :
1. Create requester class and creating a socket to connect
the sever .

Request select=new select (“localhost”,2004);


2. Get input and the output stream.
3. Communicate with server .
4. Call catch if error in try block.
5. Finally closing the connection.
6. In main() method create object for Requester class and
call`
Client.run();
Program:
SERVER:
// Save as Provider.java
import java.io.*;
import java.net.*;
public class Provider
{
ServerSocketproviderSocket;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider() {}
void run()
{
try
{
//1.creating a server socket
providerSocket =new ServerSocket(2004,10);
//2. wait for connection
System.out.println(" Waiting for connection");
connection =providerSocket.accept();
System.out.println(" Connection recevied
from"+connection.getInetAddress().getHostName());
//3.get input and output streams
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in =new ObjectInputStream(connection.getInputstream());
sendMessage("Connection successful");
//4. The two parts communicate via the input and outputstream
do
{
try
{
message =(String)in.readObject();
System.out.println("client"+message);
if(message.equals("bye"))
sendMessage("bye");
}
catch(ClassNotFoundExceptionclassnot)
{
System.err.println(" Data recevied in unknown format");
}
}while(!message.equals("bye"));
}
catch(IOExceptionioException)
{
ioException.printStackTrace();
}
finally
{
//5.Closing connection
try
{
in.close();
out.close();
providerSocket.close();
}
catch(IOExceptionioException)
{
ioException.printStackTrace();
}
}
}
voidsendMessage(String msg)
{
try
{
out.writeObject(msg);
out.flush();
System.out.println("Server->"+msg);
}
catch(IOExceptionioException)
{
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Provider server =new Provider();
while(true)
{
server.run();
}
}
}
CLIENT:
// Save as Requester.java
import java.io.*;
import java.net.*;
public class Requester{
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Requester(){}
void run()
{
try{
//1. creating a socket to connect to the server
requestSocket = new Socket("localhost", 2004);
System.out.println("Connected to localhost in port 2004");
//2. get Input and Output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
//3: Communicating with the server
do{
try{
message = (String)in.readObject();
System.out.println("server>" + message);
sendMessage("Hi my server");
message = "bye";
sendMessage(message);
}
catch(ClassNotFoundException classNot){
System.err.println("data received in unknown format");
}
}while(!message.equals("bye"));
}
catch(UnknownHostException unknownHost){
System.err.println("You are trying to connect to an unknown host!");
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("client>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Requester client = new Requester();
client.run();
}
}
SAMPLE OUTPUT:
SAMPLE OUTPUT:

Result:
Thus the program for Networking was executed and its output is
verified.
EX.NO:10 RMI

Aim:
To write a java Program to implement RMI concepts.

Algorithm:
1. Create Interface inter extends java.rmi.Remote and of
method.
2. Void fact(int n) throw java.rmi.RemoteException .
3. Create class Imple extends
Java.rmi.Server.unicast Remote objects implements Inter
4. Their constructor throws java.rmi.RmoteException .
5. And in fact(int n) method perform an operation and
display the factorial of n.
6. Create server class, in main() method create an object for
class Imple.
Java.rmi.Naming.rebing(“Server”.e);
7. In a Client class create local host .

a. Inter S=(Inter ) java.rmi.Naming lookup (“rmi ://


LocalHost /server”);
8. Get the value of a and call sfact(n).
Program:
// Save as Server.java
importjava.rmi.*;
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String args[[])throws Exception
{
Imple c=new Imple();
java.rmi.Naming.rebind("Server",c);
System.out.println("SERVER READY.....");
}
}
//Save as Client.java
importjava.rmi.*;
import java.net.*;
import java.io.*;
public class Client
{
public static void main(String args[])throws Exception
{
BufferedReaderbr =new BufferedReader(new
inputStreamReader(System.in));
Inter s=(Inter)java.rmi.Naming.lookup(:rmi://LocalHost/Server");
System.out.println("Enter the number");
int n=Integer.parseInt(br.readLine());
s.fact(n);
}
}
// Save as Imple.java
importjava.rmi.*;
import java.net.*;
importjava.rmi.server.*;
public class Imple extends java.rmi.server.UnicastRemoteObject
implements inter
{
publicImple() throws java.rmi.RemoteException
{
}
public void fact(int n)throws java.rmi.RemoteException
{
int f=1;
for(int i=1;i<=n;i++)
f=f*i;
System.out.println("Factorial of "+n+"is:"+f);
}
}

// Save as Inter.java
importjava.rmi.*;
public interface Inter extends java.rmi.Remote
{
public void fact(int n)throws java.rmi.RemoteException;
}
SAMPLE OUTPUT:

Result:
Thus the Java program for RMI was executed and its output is
verified.
EX.NO:11 AWT

Aim:
To write a Program to implement AWT concepts.

Algorithm:
1.Create basic window monitor for class extends Window
Adapter (predefined class) in that window closing (window event
e)

2.And create object for window class and call method


setvisible(),dispose() using object w.set visible(false);

3.Create tool bar frame 1 class extends frame and


implement interface ActionListener and define a constructor .

4.In the class define cut button, copy button, paste button as
button.

5.SetSize(450,250) for the label.

6.Add windowListener in the class.

7.Create an object for panel class.

8.Define and add ActionListener for all object of button


class.

9.In void action performed(ActionEventae) getAction


command is displayed.

System.out.println(ae.getActionCommand());
10. In main() method create object for ToolBarFrame and
call method setVisible (true) in a class.
Program:
//Save as BasicWindowMonitor.java
import java.awt.event.*;
import java.awt.Window;
public class BasicWindowMonitor extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window w = e.getWindow();
w.setVisible(false);
w.dispose();
System.exit(0);
}
}
// Save as ToolbarFrame.java
import java.awt.*;
import java.awt.event.*;
public class ToolbarFrame1 extends Frame implements ActionListener {
Button cutButton, copyButton, pasteButton;
public ToolbarFrame1() {
super("Toolbar Example (AWT)");
setSize(450, 250);
addWindowListener(new BasicWindowMonitor());
Panel toolbar = new Panel();
toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));
cutButton = new Button("Cut");
cutButton.addActionListener(this);
toolbar.add(cutButton);
copyButton = new Button("Copy");
copyButton.addActionListener(this);
toolbar.add(copyButton);
pasteButton = new Button("Paste");
pasteButton.addActionListener(this);
toolbar.add(pasteButton);
add(toolbar, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getActionCommand());
}
public static void main(String args[]) {
ToolbarFrame1 tf1 = new ToolbarFrame1();
tf1.setVisible(true);
}
}
SAMPLE OUTPUT:

Result:
Thus the program for performing awt was executed and its output
is verified
EX.NO: 12 SWING

Aim:
To write a Program to implement swing concepts.

Algorithm:
1.Create SApplet class extends applet implements
ActionListener
2.In that class create fields for Textfields,label,button,jlabel
and integer variables.
3.Define label and setbackground and setforeground
,thenadd it in applet.
Add(input);
4. Define textfield and add it in and button and add with
Actionlistener.
B1.add ActionListener (this);
5.Action performed (ActionEvent e) method with num.
Num=Integer.parseInt(ae.getAction command());
6.sum+=num is the event performing and display the result.
Program:
//Save as SApplet.java
/* <head><APPLET CODE="SApplet.class" HEIGHT=150
WIDTH=150>
You can not see this brilliant Java Applet.
</APPLET></body> */
//SWING
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SApplet extends Applet implements ActionListener {
TextField input,output;
Label label1,label2;
Button b1;
JLabel lbl;
int num, sum = 0;
public void init(){
label1 = new Label("Please Enter number : ");
add(label1);
label1.setBackground(Color.yellow);
label1.setForeground(Color.magenta);
input = new TextField(5);
add(input);
label2 = new Label("Sum : ");
add(label2);
label2.setBackground(Color.yellow);
label2.setForeground(Color.magenta);
output = new TextField(20);
add(output);
// input.addActionListener( this );
b1 = new Button("Add");
add(b1);
b1.addActionListener(this);
lbl = new JLabel("This is the Swing Applet Example. ");
add(lbl);
setBackground(Color.yellow);
// output.addActionListener( this );
}
public void actionPerformed(ActionEvent ae){
try{
// num = Integer.parseInt(ae.getActionCommand());
num = Integer.parseInt(input.getText());
sum = sum+num;
input.setText("");
output.setText(Integer.toString(sum));
lbl.setForeground(Color.blue);
lbl.setText("Output of the Second Text Box : " + output.getText());
}
catch(NumberFormatException e){
lbl.setForeground(Color.red);
lbl.setText("Invalid Entry!");
}
}
}
SAMPLE OUTPUT:

Result:
Thus the program for performing swing was executed and its
output is verified.
EX.NO:13 APPLET

Aim:
To write a Program to design and implement applet.

Algorithm:
1.CreateHelloWorld class extends applet (predefined
class).
2.Declare the method init() and paint (Graphics g).
3. Set setFont and drawstring using object g.
4.Write html to run the applet program
Program:
// Save as HELLOWORLD.java
import java.applet.*;
import java.awt.*;
public class HELLOWORLD extends Applet
{
public void init()
{
resize(150,25);
}
public void paint(Graphics g)
{
g.setFont(new Font("Helvetica",Font.PLAIN,18));
g.drawString("HELLOWORLD!!!",50,25);
}
}
/* <head><APPLET CODE ="HELLOWORLD.class" HEIGHT=150
WIDTH=150>
youcan not see this brilliant java applet
</APPLET></body>*/
SAMPLE OUPUT:

Result:
Thus the program for applet was executed and its output is
verified.
EX.NO:14 JDBC WITH MY SQL

Aim:
To write a java Program to design and implement JDBC

Algorithm:
1. Create a class Registration extends JFrame and implements
ActionListener
2. Declare the object for JLabel, JTextField, JButton and
JPasswordFields
3. Using the constructor create and Registration from using awt
class and the methods.
4. Declare the method actionPerformed (ActionEvent e) that
perform to get the input from the Registration and action
performed for click events.
5. Using the object can for Class connection store the details in
xml file
6. Declare main() class and call constructor for Registration
class new Registration.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Registration extends JFrame implements ActionListener
{
JLabel l1, l2, l3, l4, l5, l6, l7, l8;
JTextField tf1, tf2, tf5, tf6, tf7;
JButton btn1, btn2;
JPasswordField p1, p2;
Registration()
{
setVisible(true);
setSize(700, 700);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Registration Form in Java");
l1 = new JLabel("Registration Form in Windows Form:");
l1.setForeground(Color.blue);
l1.setFont(new Font("Serif", Font.BOLD, 20));
l2 = new JLabel("Name:");
l3 = new JLabel("Email-ID:");
l4 = new JLabel("Create Passowrd:");
l5 = new JLabel("Confirm Password:");
l6 = new JLabel("Country:");
l7 = new JLabel("State:");
l8 = new JLabel("Phone No:");
tf1 = new JTextField();
tf2 = new JTextField();
p1 = new JPasswordField();
p2 = new JPasswordField();
tf5 = new JTextField();
tf6 = new JTextField();
tf7 = new JTextField();
btn1 = new JButton("Submit");
btn2 = new JButton("Clear");
btn1.addActionListener(this);
btn2.addActionListener(this);
l1.setBounds(100, 30, 400, 30);
l2.setBounds(80, 70, 200, 30);
l3.setBounds(80, 110, 200, 30);
l4.setBounds(80, 150, 200, 30);
l5.setBounds(80, 190, 200, 30);
l6.setBounds(80, 230, 200, 30);
l7.setBounds(80, 270, 200, 30);
l8.setBounds(80, 310, 200, 30);
tf1.setBounds(300, 70, 200, 30);
tf2.setBounds(300, 110, 200, 30);
p1.setBounds(300, 150, 200, 30);
p2.setBounds(300, 190, 200, 30);
tf5.setBounds(300, 230, 200, 30);
tf6.setBounds(300, 270, 200, 30);
tf7.setBounds(300, 310, 200, 30);
btn1.setBounds(50, 350, 100, 30);
btn2.setBounds(170, 350, 100, 30);
add(l1);
add(l2);
add(tf1);
add(l3);
add(tf2);
add(l4);
add(p1);
add(l5);
add(p2);
add(l6);
add(tf5);
add(l7);
add(tf6);
add(l8);
add(tf7);
add(btn1);
add(btn2);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == btn1)
{
int x = 0;
String s1 = tf1.getText();
String s2 = tf2.getText();
char[] s3 = p1.getPassword();
char[] s4 = p2.getPassword();
String s8 = new String(s3);
String s9 = new String(s4);
String s5 = tf5.getText();
String s6 = tf6.getText();
String s7 = tf7.getText();
if (s8.equals(s9))
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@mcndesktop07:1521:x
e", "sandeep", "welcome");
PreparedStatementps = con.prepareStatement("insert into reg
values(?,?,?,?,?,?)");
ps.setString(1, s1);
ps.setString(2, s2);
ps.setString(3, s8);
ps.setString(4, s5);
ps.setString(5, s6);
ps.setString(6, s7);
ResultSetrs = ps.executeQuery();
x++;
if (x > 0)
{
JOptionPane.showMessageDialog(btn1, "Data Saved
Successfully");
}
}
catch (Exception ex)
{
System.out.println(ex);
}
}
else
{
JOptionPane.showMessageDialog(btn1, "Password Does Not
Match");
} }
else
{
tf1.setText("");
tf2.setText("");
p1.setText("");
p2.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
}
}
public static void main(String args[])
{
new Registration();
}
}
SAMPLE OUTPUT:
Result:
Thus the Program implement JDBC was executed and its output is
verified
EX.NO:15 CALCULATOR
Aim:
To write a java Program to design an event handling event
for simulating a simple calculator.

Algorithm:
1. Create a class Calculator extends JFrame implements
ActionListener, declare the variable for JTextArea, Font,JPanel and
JButton.
2. Using Constructor create a virtual calculator of design
with the use of methods using classes
“java.awt.* javax.swing.* java.awt.event.*”
3. Declare the method actionPerformed(ActionEventae) to
handle the click event in Calculator
4. Get the input from textField and from the button
5. Display the Result in TextField
Program:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
JPanel[] row=new JPanel[5];
JButton[] button =new JButton[19];
String[]buttonString ={"7","8","9","+","4","5","6","-
","1","2","3","*",".",",","/","C","+/-","=","0"};
int[] dimW={300,45,100,90};
int[] dimH={35,40};
Dimension displayDimension=new Dimension(dimW[0],dimH[0]);
Dimension regularDimension=new Dimension(dimW[1],dimH[1]);
Dimension rColumnDimension=new Dimension(dimW[2],dimH[1]);
Dimension ZeroButDimension=new Dimension(dimW[3],dimH[1]);
boolean[] function=new boolean[4];
double[] temporary ={0,0};
JTextArea display=new JTextArea(1,20);
Font font=new Font("Times new Roman",Font.BOLD,14);
Calculator()
{
super("Calculator");
setDesign();
setSize(380,250);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid=new GridLayout(5,5);
setLayout(grid);
for(int i=0;i<4;i++)
function[i]=false;
FlowLayout f1=new FlowLayout(FlowLayout.CENTER);
FlowLayout f2=new FlowLayout(FlowLayout.CENTER,1,1);
for(int i=0;i<5;i++)
row[i]=new JPanel();
row[0].setLayout(f1);
for(int i=0;i<5;i++)
row[i].setLayout(f2);
for(int i=0;i<19;i++)
{
button[i]=new JButton();
button[i].setText(buttonString[i]);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_L
EFT);
display.setPreferredSize(displayDimension);
for(int i=0;i<14;i++)
button[i].setPreferredSize(regularDimension);
for(int i=14;i<18;i++)
{button[i].setPreferredSize(rColumnDimension);
button[i].setPreferredSize(ZeroButDimension);
row[0].add(display);
add(row[0]);
}
for(int i=0;i<4;i++)
row[1].add(button[i]);
row[1].add(button[14]);
add(row[1]);
for(int i=4;i<8;i++)
row[2].add(button[i]);
row[2].add(button[15]);
add(row[2]);
for(int i=8;i<12;i++)
row[3].add(button[i]);
row[3].add(button[16]);
add(row[3]);
row[4].add(button[18]);
for(int i=12;i<14;i++)
row[4].add(button[i]);
row[4].add(button[17]);
add(row[4]);
setVisible(true);
}
public void clear()
{
try
{
display.setText("");
for(int i=0;i<4;i++)
function[i]=false;
for(int i=0;i<2;i++)
temporary[i]=0;
}
catch(NullPointerException e)
{
}
}
public void getSqrt()
{
try
{
double value=Math.sqrt(Double.parseDouble(display.getText()));
display.setText(Double.toString(value));
}catch(NumberFormatException e){
}
}
public void getPosNeg(){
try {
double value=Double.parseDouble(display.getText());
if(value!=0)
{
value=value*(-1);
display.setText(Double.toString(value));
}
else {
}
}catch(NumberFormatException e) {
}
}
public void getResult() {
double result =0;
temporary[1]=Double.parseDouble(display.getText());
String temp0=Double.toString(temporary[0]);
String temp1=Double.toString(temporary[1]);
try{
if(temp0.contains("-")) {
String[] temp2=temp0.split("-",2);
temporary[0]=(Double.parseDouble(temp2[1])*-1);
}
if(temp1.contains("-")) {
String[] temp3=temp1.split("-",2);
temporary[1]=(Double.parseDouble(temp3[1])*-1);
}
}catch(ArrayIndexOutOfBoundsException e) {
}
try {
if(function[2]==true)
result=temporary[0]*temporary[1];
else if(function[3]==true)
result=temporary[0]/temporary[1];
else if(function[0]==true)
result=temporary[0]+temporary[1];
else if(function[1]==true)
result=temporary[0]-temporary[1];
display.setText(Double.toString(result));
for(int i=0;i<4;i++)
function[i]=false;
}catch(NumberFormatException e) {
}
}
public final void setDesign()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLo
okAndFeel");
}
catch(Exception e) {
}
}
@Override
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==button[0])
display.append("7");
if(ae.getSource()==button[1])
display.append("8");
if(ae.getSource()==button[2])
display.append("9");
if(ae.getSource()==button[3]) {
// add function[0]
temporary[0]=Double.parseDouble(display.getText());
function[0]=true;
display.setText("");
}
if(ae.getSource()==button[4])
display.append("4");
if(ae.getSource()==button[5])
display.append("5");
if(ae.getSource()==button[6])
display.append("6");
if(ae.getSource()==button[7]) {
// subtract function[1]
temporary[0]=Double.parseDouble(display.getText());
function[1]=true;
display.setText("");
}
if(ae.getSource()==button[8])
display.append("1");
if(ae.getSource()==button[9])
display.append("2");
if(ae.getSource()==button[10])
display.append("3");
if(ae.getSource()==button[11]) {
// multiply function[2]
temporary[0]=Double.parseDouble(display.getText());
function[2]=true;
display.setText("");
}
if(ae.getSource()==button[12])
display.append(".");
if(ae.getSource()==button[13]) {
// divide function[3]
temporary[0]=Double.parseDouble(display.getText());
function[3]=true;
display.setText("");
}
if(ae.getSource()==button[14])
clear();
if(ae.getSource()==button[15])
getSqrt();
if(ae.getSource()==button[16])
getPosNeg();
if(ae.getSource()==button[17])
getResult();
if(ae.getSource()==button[18])
display.append("0");
}
public static void main(String [] arguements)
{
Calculator c= new Calculator();
}
}
SAMPLE OUTPUT:

MULTIPLICATION:9*2=18

Result:
Thus the Program to design an event handling event for simulating
a simple calculator was executed and its output is verified.

You might also like