Vous êtes sur la page 1sur 49

DEPARTMENT OF INFORMATION TECHNOLOGY

16PBIC52–PRACTICAL – JAVA PROGRAMMING

YEAR 2018-2019

NAME OF THE STUDENT :


REGISTER NUMBER :
COURSE :
YEAR :
SEMESTER :

1
VELS
VELS INSTITUTE OF SCIENCE, TECHNOLOGY AND ADVANCED STUDIES
(VISTAS)
Deemed to be University Estd. U/S 3 of the UGC ACT, 1956
NAAC ACCREDITED
PALLAVARAM,CHENNAI

BONAFIDE CERTIFICATE

Reg.No.

This is to certify that the Bonafide Record of this Practical Work was completed
by

Mr./Ms…………………………………………………..B.TECH IN IT
CLOUD AND MOBILE BASED APPLICATION DEVELOPMENT in
the Java Programming Laboratory during the academic year of 2018-2019.

HEAD OF THE DEPARTMENT STAFF-IN-

CHARGE

Submitted for the Practical Examination held on …………………………..

INTERNAL EXAMINER EXTERNAL

EXAMINER

2
CONTENTS

Ex No Date Title Page No Remarks

IMPLEMENTATION OF RATIONAL
01 NUMBERS 3

IMPLEMENTATION OF DATE
02 CLASS 5

IMPLEMENTATION OF LISP-LIKE-
LIST
03 7

IMPLEMENTATION OF JAVA
INTERFACE FOR ADT STACK
04 9

IMPLEMENTATION OF
POLYMORPHISM
05 13

IMPLEMENTATION OF OBJECT
06 SERILIZATION 16

IMPLEMENTATION OF SCENTIFIC
CALCULATOR USING EVENT
07 20
DRIVEN PROGRAMMING

IMPLEMENTATION OF MULTI
08 THREADED PROGRAM 25

PROGRAM FOR SIMPLE OPAC


09 SYSTEM FOR LIBRARY 29

IMPLEMENTATION OF MULTI-
10 THREADED ECHO SERVER 34

3
PROGRAM:

import java.io.*;
public class rat
{
public static void main(String[] args)
{
Rational a=new Rational(35,50);
System.out.println("\na="+a);
}
}
class Rational
{
public Rational(int num,int denum)
{
numerator=num;
if(denum==0)
denuminator=1;
else
denuminator=denum;
makeRational();
}
private void makeRational()
{
int gcd;
int divisor=0;
if(denuminator<0)
{
numerator=numerator*-1;
denuminator=denuminator*-1;
}
gcd=greatestCommonDivisor(Math.abs(numerator),denuminator);
numerator=numerator/gcd;
denuminator=denuminator/gcd;
}
private int greatestCommonDivisor(int n,int d)
{
int remainder=n %d;
while(remainder!=0)
{
n=d;
d=remainder;
remainder=n%d;
}
return d;
}
public String toString()
{
String result=EMPTY_STRING;
if(denuminator==1)
result=String.valueOf(numerator);

4
else
{
result=result.concat(String.valueOf(numerator));
result=result.concat("/");
result=result.concat(String.valueOf(denuminator));
}
return result;
}
private static final String EMPTY_STRING="";
private int numerator;
private int denuminator;
}

5
OUTPUT:

C:\jdk1.6.0_17\bin>javac rat.java
C:\jdk1.6.0_17\bin>java rat
a=7/10

6
RESULT:
Thus the program Implementation of rational numbers has been successfully
executed verified and successfully

7
PROGRAM:

import java.io.*;
import java.util.Date;
public class Dateclass
{
public static void main(String args[])
{
Date d1=new Date();
try
{
Thread.sleep(10);
}
catch(Exception e)
{
}
Date d2=new Date();
System.out.println("First date:"+d1);
System.out.println("Second date:"+d2);
System.out.println("In second date after first:"+d2.after(d1));
int result=d1.compareTo(d2);
if(result>0)
System.out.println("First date is after second date");
else if(result<0)
System.out.println("First date is before second date");
else
System.out.println("Both are equal");
Date d=new Date(365L*24L*60L*60L*1000L);
System.out.println(d);
System.out.println("Milli Second since jan-1-1970 00:00:00:IST:"+d.getTime());
}
}

8
OUTPUT:

C:\ jdk1.6.0_17\bin>javac DateClass.java


C:\jdk1.6.0_17\bin>java DateClass
First date:Wed Sep 29 20:23:17 GMT+05:30 2010
Second date:Wed Sep 29 20:23:17 GMT+05:30 2010
In second date after first:true
First date is before second date
Fri Jan 01 05:30:00 GMT+05:30 1971
Milli Second since jan-1-1970 00:00:00:IST:31536000000

9
RESULT:

Thus the program Implementation of date class has been successfully executed
verified and successfully.

10
PROGRAM:

import java.util.*;
class Lisp
{
public int car(List l)
{
Object ob=l.get(0);
String st=ob.toString();
return Integer.parseInt(st);
}
public List cdr(List l)
{
Object ob=l.remove(0);
Object obj[]=l.toArray();
List list=Arrays.asList(obj);
return list;
}
public static void main(String[] args)
{
List <Integer>l=new ArrayList<Integer>();
l.add(3);
l.add(0);
l.add(2);
l.add(5);
Lisp L=new Lisp();
int val=L.car(l);
System.out.println(val);
List list=L.cdr(l);
System.out.println(list);
}
}

11
OUTPUT:

C:\jdk1.6.0_17\bin>javac Lisp.java
C:\jdk1.6.0_17\bin>java Lisp
3
[0, 2, 5]
C:\jdk1.6.0_17\bin>

12
RESULT:

Thus the program Implementation of lisp-like-list has been successfully executed


verified and successfully

13
PROGRAM:

import java.util.*;
public class ListStack implements Stack
{
public ListStack()
{
topOfStack=null;
}
public boolean isEmpty()
{
return topOfStack==null;
}
public void push(Object x)
{
topOfStack=new ListNode(x,topOfStack);
}
public void pop()
{
if(isEmpty())
throw new UnderflowException("ListStack pop");
System.out.println(topOfStack.element+"is deleted");
topOfStack=topOfStack.next;
}
public void display()
{
DispNode=topOfStack;
while(DispNode!=null)
{
System.out.println(DispNode.element+" ");
DispNode=DispNode.next;
}
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
ListStack theList=new ListStack();
int data=10;
int choice;
do
{
System.out.println();
System.out.println("-------------------------------------------------------------------");

System.out.println("STACK IMPLEMENTATION USING LINKED LIST");


System.out.println("-------------------------------------------------------------------");
System.out.println();
System.out.println("1.PUSH");
System.out.println("2.POP");
System.out.println("3.DISPLAY");
System.out.println("4.EXIT");

14
System.out.println("\n ENTER YOUR CHOICE:");
choice=in.nextInt();
switch(choice)
{
case 1:
System.out.println("\n enter the element to push:");
data=in.nextInt();
theList.push(data);
break;
case 2:
theList.pop();
break;
case 3:
System.out.println("the Stack elements are:");
theList.display();
break;
case 4:
break;
default:
System.out.println("wrong choice");
}
}
while(choice!=4);
}
private ListNode topOfStack;
private ListNode DispNode;
}
class UnderflowException extends RuntimeException
{
public UnderflowException(String message)
{
super(message);
}
}
interface Stack
{
void push(Object x);
void pop();
void display();
boolean isEmpty();
}
class ListNode
{
public ListNode(Object theElement)
{
this(theElement,null);
}
public ListNode(Object theElement,ListNode n)
{
element=theElement;
next=n;

15
}
public Object element;
public ListNode next;
}

16
OUTPUT:

C:\jdk1.6.0_17\bin>javac ListStack.java
C:\jdk1.6.0_17\bin>java ListStack
------------------------------------------------------------------
STACK IMPLEMENTATION USING LINKED LIST
------------------------------------------------------------------
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR OPTION:1
Enter the element to push:100
-------------------------------------------------------------------
STACK IMPLEMENTATION USING LINKED LIST
-------------------------------------------------------------------
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR OPTION:3
100
-------------------------------------------------------------------
STACK IMPLEMENTATION USING LINKED LIST
-------------------------------------------------------------------
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR OPTION:2
100is deleted
-------------------------------------------------------------------
STACK IMPLEMENTATION USING LINKED LIST
-------------------------------------------------------------------
1. PUSH
2. POP
3. DISPLAY
4. EXIT
ENTER YOUR OPTION:3
-------------------------------------------------------------------
STACK IMPLEMENTATION USING LINKED LIST
-------------------------------------------------------------------
1. PUSH
2. POP
3. DISPLAY
4. EXIT

17
RESULT:

Thus the program Implementation of java interface for ADT stack has been successfully
executed verified and successfully.

18
PROGRAM:

import java.io.*;
public class VehicleTest
{
public static void main(String[] args)
{
Vehicle corvette=new Corvette("Corvette","red",545000);
Vehicle bettle=new Bettle("Bettle","blue",445000);
Vehicle porsche=new Porsche("Porsche","black",625000);
Vehicle vehicle=new Vehicle();
vehicle=porsche;
System.out.println("Name="+corvette.getName()+"\nColor="+corvette.getColor()+"\nP
rice="+corvette.getPrice()+"\n\n");
System.out.println("Name="+bettle.getName()+"\nColor="+bettle.getColor()+"\nPrice=
"+bettle.getPrice()+"\n\n");
System.out.println("Name="+porsche.getName()+"\nColor="+porsche.getColor()+"\nP
rice="+porsche.getPrice()+"\n\n");
}
}
class Vehicle
{
String name;
String color;
double price;
public Vehicle()
{
name="";
color=" ";
price=0;
}
public Vehicle(String name,String color,double price)
{
this.name=name;
this.color=color;
this.price=price;
}
public String getName()
{
return name;
}
public String getColor()
{
return color;
}
public double getPrice()
{
return price;
}
}
class Bettle extends Vehicle

19
{
public Bettle(String name,String color,double price)
{
super(name,color,price);
}
}
class Corvette extends Vehicle
{
public Corvette(String name,String color,double price)
{
super(name,color,price);
}
}
class Porsche extends Vehicle
{
public Porsche(String name,String color,double price)
{
super(name,color,price);
}
}

20
OUTPUT:

C:\jdk1.6.0_17\bin>javac VehicleTest.java
C:\jdk1.6.0_17\bin>java VehicleTest
Name=Corvette
Color=red
Price=545000.0

Name=Bettle
Color=blue
Price=445000.0

Name=Porsche
Color=black
Price=625000.0
C:\jdk1.6.0_17\bin>

21
RESULT:

Thus the program Implementation of polymorphism has been successfully executed


verified and successfully.

22
PROGRAM:
import java.util.*;
import java.io.ObjectOutput;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

class Rupee
{
public Rupee()
{
try
{
Object object=new Object();
object="45";
ObjectOutput out=new ObjectOutputStream(new FileOutputStream("Rupees.dat"));
out.writeObject(object);
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Dollar
{
public Dollar()
{
try
{
Object object=new Object();
object="45";
ObjectOutput out=new ObjectOutputStream(new FileOutputStream("Dollar.dat"));
out.writeObject(object);
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public class Currency
{
public static void main(String args[])
{
new Rupee();
new Dollar();
}
}

23
//CURRENCY TEST
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.*;
public class CurrencyTest
{
public static void main(String[] args)
{
System.out.println("Select Input Type");
System.out.println("\n1.Dollar\n2.Rupee\n\n");
Scanner input=new Scanner(System.in);
int choice=input.nextInt();
if(choice==1)
{
System.out.println("Enter No of Dollar:");
int noDollar=input.nextInt();
String value="";
String filename="Dollar.dat";
FileInputStream fis=null;
ObjectInputStream in=null;
try
{
fis=new FileInputStream(filename);
in=new ObjectInputStream(fis);
value=(String)in.readObject();
in.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
System.out.println("The Equal Rupee is:"+noDollar*(Integer.parseInt(value)));
System.out.println();
}
else if(choice==2)
{
System.out.println("Enter Rupee:");
int noRupee=input.nextInt();
System.out.println("The Rupee is:"+noRupee);
System.out.println();
}
}
}

24
OUTPUT:

C:\jdk1.6.0_17\bin>javac Currency.java
C:\jdk1.6.0_17\bin>java Currency

C:\jdk1.6.0_17\bin>javac CurrencyTest.java
C:\jdk1.6.0_17\bin>java CurrencyTest
Select Input Type

1.Dollar
2.Rupee

1
Enter No of Dollar:
45
The Equal Rupee is:2025
C:\jdk1.6.0_17\bin>java CurrencyTest
Select Input Type

1.Dollar
2.Rupee

2
Enter Rupee:
45
The Rupee is:45
C:\jdk1.6.0_17\bin>

25
RESULT:

Thus the program Implementation object serialization has been successfully executed
verified and successfully.

26
PROGRAM:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class Calculator
{
public static void main(String[] args)
{
CalculatorFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class CalculatorFrame extends JFrame
{
public CalculatorFrame()
{
setTitle("Calculator");
CalculatorPanel panel = new CalculatorPanel();
add(panel);
pack();
}
}
class CalculatorPanel extends JPanel
{
public CalculatorPanel()
{
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
display = new JButton("0");
display.setEnabled(false);
add(display, BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
panel = new JPanel();
panel.setLayout(new GridLayout(6,5));

addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("CE", command);

addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);

27
addButton("m+", command);

addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("m-", command);

addButton("0", insert);
addButton(".", insert);
addButton("+/-", command);
addButton("+", command);
addButton("n!", command);

addButton("pow", command);
addButton("1/x", insert);
addButton("SQRT", insert);
addButton("log", insert);
addButton("%", command);

addButton("sin", insert);
addButton("cos", insert);
addButton("tan", insert);
addButton("x2", insert);
addButton("=", command);

add(panel, BorderLayout.CENTER);
}
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
if (start==true)
{
display.setText("");
start = false;
}
if(input.equals("1/x"))
display.setText(""+1/Double.parseDouble(display.getText()));
else
if(input.equals("SQRT"))
display.setText(""+Math.sqrt(Double.parseDouble(display.getText())));

else

28
if(input.equals("log"))
display.setText(""+Math.log(Double.parseDouble(display.getText())));

else
if(input.equals("x2"))
display.setText(""+Double.parseDouble(display.getText())*
Double.parseDouble(display.getText()));

else
if(input.equals("sin"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.sin(angle));
}
else if(input.equals("cos"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.cos(angle));
}
else
if(input.equals("tan"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.tan(angle));
}
else
display.setText(display.getText() + input);
}
}
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();

if (start==true)
{
if (command.equals("-"))
{
display.setText(command);
start = false;
}
else
lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}

29
}
}
public void calculate(double x)
{
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
else if (lastCommand.equals("CE")) result = 0.0;
else if (lastCommand.equals("m+")) result = result;
else if (lastCommand.equals("m-")) result = 0.0;
else if (lastCommand.equals("pow"))
{
double powval=1.0;
for(double i=0.0;i<x;i++)
powval*=result;
result=powval;
}
display.setText(""+ result);
}
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}

30
OUTPUT:

C:\jdk1.6.0_17\bin>javac Calculator.java
C:\jdk1.6.0_17\bin>java Calculator
C:\jdk1.6.0_17\bin>

31
RESULT:

Thus the program Implementation of scientific calculator using event driven


programming has been successfully executed verified and successfully.

32
PROGRAM:

import java.util.*;
import java.io.*;
class Fibonacci extends Thread
{
private PipedWriter out=new PipedWriter();
public PipedWriter getPipedWriter()
{
return out;
}
public void run()
{
Thread t=Thread.currentThread();
t.setName("Fibonacci:");
System.out.println(t.getName()+"Thread stored......");
int fibo1=0,fibo2=1,fibo=0;
while(true)
{
try
{
fibo=fibo1+fibo2;
if(fibo>100000)
{
out.close();
break;
}
out.write(fibo);
sleep(1000);

}
catch(Exception e)
{
System.out.println("Fibonacci:"+e);
}
fibo1=fibo2;
fibo2=fibo;
}
System.out.println(t.getName()+"Thread exiting.");
}
}
class Prime extends Thread
{
private PipedWriter out1=new PipedWriter();
public PipedWriter getPipedWriter()
{
return out1;
}
public void run()
{
Thread t=Thread.currentThread();

33
t.setName("Prime:");
System.out.println(t.getName()+"Thread stored.......");
int prime=1;
while(true)
{
try
{
if(prime>100000)
{
out1.close();
break;
}
if(isPrime(prime))
out1.write(prime);
prime++;
sleep(0);
}
catch(Exception e)
{
System.out.println(t.getName()+"Thread exiting.");
System.exit(0);
}
} }
public boolean isPrime(int n)
{
int m=(int)Math.round(Math.sqrt(n));
if(n==1||n==2)
return true;
for(int i=2;i<=m;i++)
if(n%i==0)
return false;
return true;
}
}
public class PipedIo
{
public static void main(String[] args)throws Exception
{
Thread t=Thread.currentThread();
t.setName("Main:");
System.out.println(t.getName()+"Thread sorted......");
Fibonacci fibonacci=new Fibonacci();
Prime prime=new Prime();
PipedReader fpr=new PipedReader(fibonacci.getPipedWriter());
PipedReader ppr=new PipedReader(prime.getPipedWriter());
fibonacci.start();
prime.start();
int fib=fpr.read(),prm=ppr.read();
System.out.println("The Numbers Common To PRIME and FIBONACCI:");
while ((fib!=-1)&&(prm!=-1))
{

34
while(prm<=fib)
{
if(fib==prm)
System.out.println(prm);
prm=ppr.read();
}
fib=fpr.read();
}
System.out.println(t.getName()+"Thread exiting.");
} }

35
OUTPUT:

C:\jdk1.6.0_17\bin>javac PipedIo.java

C:\jdk1.6.0_17\bin>java PipedIo
Main:Thread sorted......
Fibonacci:Thread stored......
Prime:Thread stored.......
The Numbers Common To PRIME and FIBONACCI:
1
2
3
5
13
89
233
1597
28657
Fibonacci:Thread exiting.
Main:Thread exiting.
Prime:Thread exiting.

C:\jdk1.6.0_17\bin>

36
RESULT:

Thus the program Implementation of multi threaded program to find Fibonacci series
has been Successfully executed and verified successfully.

37
EVENT DRIVEN:

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Datas extends JFrame implements ActionListener
{
JTextField id;
JTextField name;
JButton next;
JButton addnew;
JPanel p;
static ResultSet res;
static Connection conn;
static Statement stat;
public Datas()
{
super("Our Application");
Container c = getContentPane();
c.setLayout(new GridLayout(5,1));
id = new JTextField(20);
name = new JTextField(20);
next = new JButton("Next BOOK");
p = new JPanel();
c.add(new JLabel("ISBN",JLabel.CENTER));
c.add(id);
c.add(new JLabel("Book Name",JLabel.CENTER));
c.add(name);
c.add(p);
p.add(next);
next.addActionListener(this);
pack();
setVisible(true);
addWindowListener(new WIN());
}
public static void main(String args[])
{
Datas d = new Datas();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:custo"); // custo is the DSN Name
stat = conn.createStatement();
res = stat.executeQuery("Select * from Customers"); // Customers is the table name
res.next();
}
catch(Exception e)
{
System.out.println("Error" +e);
}

38
d.showRecord(res);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == next)
{
try
{
res.next();
}
catch(Exception ee) {}
showRecord(res);
}
}
public void showRecord(ResultSet res)
{
try
{
id.setText(res.getString(1));
name.setText(res.getString(2));
}
catch(Exception e) {}
}
class WIN extends WindowAdapter
{
public void windowClosing(WindowEvent w)
{
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSA
GE);
}
} //end of WIN class
}//end of Datas class

39
OUTPUT:

D:\ Java\jdk1.5.0_03\bin>javac Datas.java


D:\ Java\jdk1.5.0_03\bin>java Datas

40
CONCURRENT PROGRAMMING:

import java.sql.*;
import java.sql.DriverManager.*;
class Ja
{
String bookid,bookname;
int booksno;
Connection con;
Statement stmt;
ResultSet rs;
Ja()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:cust");
}
catch(Exception e)
{
System.out.println("connection error");
}
}
void myput()
{
try
{
stmt=con.createStatement();
rs=stmt.executeQuery("SELECT * FROM cust1");
while(rs.next())
{
booksno=rs.getInt(1);
bookid=rs.getString(2);
bookname=rs.getString(3);
System.out.println("\n"+ booksno+"\t"+bookid+"\t"+bookname);
}
rs.close();
stmt.close();
con.close();
}
catch(SQLException e)
{
System.out.println("sql error");
}
}
}

class prog1
{
public static void main(String arg[])
{

41
Ja j=new Ja();
j.myput();
}
}

42
OUTPUT:

D:\ Java\jdk1.5.0_03\bin>javac Ja.java


D:\ Java\jdk1.5.0_03\bin>java prog1

1 10 JAVA

2 20 C++

3 30 C#

43
RESULT:

Thus the program Implementation of simple OPAC system for library has been
Successfully executed and verified successfully.

44
PROGRAM:
//SERVER
import java .io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleThreadedSocketListener
{
ServerSocket server;
int serverPort=8888;
public SimpleThreadedSocketListener()
{
try
{
server=new ServerSocket(serverPort);
System.out.println("ServerSocket:"+server);
}
catch(IOException e)
{
e.printStackTrace();
}
}
private void listen()
{
while(true)
{
try
{
Socket socket=server.accept();
System.out.println("Socket:"+socket);
new ClientThread(socket).start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String[]args)
{
new SimpleThreadedSocketListener().listen();
}
class ClientThread extends Thread
{
Socket socket;
public ClientThread(Socket socket)
{
this.socket=socket;
}
public void run()
{
InputStream in;

45
try
{
in=socket.getInputStream();
int byteRead;
while((byteRead=in.read())!=-1)
{
System.out.print((char)byteRead);
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
//CLIENT
import java .io.*;
import java .awt.*;
import java .awt.event.*;
import java .net.*;
import javax.swing.*;
public class SimpleClient extends JFrame implements ActionListener
{
Socket client=null;
String serverAddr="localhost";
int serverPort=8888;
PrintWriter out;
JTextField tf;
public SimpleClient()
{
Try
{
client=new Socket(serverAddr,serverPort);
System.out.println("Client:"+client);
out=new PrintWriter(client.getOutputStream());
out.println("HELLOW");
out.flush();
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
Container cp=this.getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.LEFT,15,15));
cp.add(new JLabel("Enter your message or\"quit\""));
tf=new JTextField(40);

46
tf.addActionListener(this);
cp.add(tf);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setTitle("simple Client");
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String message=tf.getText();
System.out.println(message);
if(message.equals("quit"))
{
try
{
out.close();
client.close();
System.exit(0);
}
catch(IOException e1)
{
e1.printStackTrace();
}
}
else
{
out.println(message);
out.flush();
tf.setText("");
}
}
public static void main(String[] args)
{
new SimpleClient();
}
}

47
OUTPUT:

C:\jdk1.6.0_17\bin>javac SimpleClient.java
C:\jdk1.6.0_17\bin>java SimpleClient
Client:Socket[addr=localhost/127.0.0.1,port=8888,localport=1040]

C:\jdk1.6.0_17\bin>javac SimpleThreadedSocketListener.java
C:\jdk1.6.0_17\bin>java SimpleThreadedSocketListener

ServerSocket:ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=8888]
Socket:Socket[addr=/127.0.0.1,port=1040,localport=8888]

HELLOW
raja
ramu
rajesh
ramki

C:\jdk1.6.0_17\bin>

48
RESULT:

Thus the program Implementation of multi threaded echo server has been successfully
executed verified and successfully.

49

Vous aimerez peut-être aussi