Anda di halaman 1dari 51

EX: NO.

1 DATE:
AIM:

Rational number class in Java

To develop a Rational number class in Java, using JavaDoc comments for documentation. The implementation should use efficient representation for a rational number, i.e. (500 / 1000) should be represented as (). ALGORITHM: Step 1: Start the program. Step 2: Define a class with two integer data fields numerator and denominator. Step 3: Define a constructor to initialize the rational number and to simplify it. Step 4: Define methods to perform the basic arithmetic operations such as addition, subtraction, multiplication, division and reciprocal. Step 5: Call the appropriate functions with the corresponding arguments and display the result. Step 6: Stop the program.

PROGRAM: import java.io.*; import java.math.*; public class TestRationalClass { private int num; private int den; public TestRationalClass(int numerator,int denominator) { if(denominator==0) { throw new RuntimeException("denominator is zero!"); } int g=gcd(numerator,denominator); num=numerator /g; den=denominator /g; } public String toString() { if(den==1) { return(num+" "); } else { return(" "+den); } } public TestRationalClass times(TestRationalClass b) { return new TestRationalClass(this.num*b.num,this.den*b.den); } public TestRationalClass plus(TestRationalClass b) { int numerator=(this.num*b.den)+(this.den*b.num); int denominator=this.den*b.den; return new TestRationalClass(numerator,denominator);

} public TestRationalClass subtract(TestRationalClass b) { int numerator=(this.num*b.den)-(this.den*b.num); int denominator=this.den*b.den; return new TestRationalClass(numerator,denominator); } public TestRationalClass reciprocal() { return new TestRationalClass(den,num); } public TestRationalClass divides(TestRationalClass b) { return this.times(b.reciprocal()); } private static int gcd(int m,int n) { if(0==n) return m; else return(gcd(n,m%n)); } public static void main(String [] args) { TestRationalClass r1=new TestRationalClass(16,2); TestRationalClass r2=new TestRationalClass(12,3); System.out.println("Rational numbers class"); System.out.println(r1 +" + "+r2+ " = "+r1.plus(r2)); System.out.println(r1 +" - "+r2+ " = "+r1.subtract(r2)); System.out.println(r1 +" * "+r2+ " = "+r1.times(r2)); System.out.println(r1 +" / "+r2+ " = "+r1.divides(r2)); } }

OUTPUT:

RESULT: Thus the program to develop a rational number class with methods to perform the basic arithmetic operations was executed and the output was verified successfully.

EX: NO. 2 DATE:


AIM:

Date class in Java

To develop Date class in Java similar to the one available in java.util package. Use JavaDoc comments. ALGORITHM: Step 1: Start the program. Step 2: Define an object today to the Date class and store the current date in that object. Step 3: Change the Date Format to Short, Long and Medium and display the date. Step 4: Convert the Date to String and print it. Step 5: Stop the program.

PROGRAM: import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class BasicDateFormatting { public static void main(String[] args)throws Exception { Date today=Calendar.getInstance().getTime(); DateFormat shortFormatter= SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT); DateFormat longFormatter= SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG); DateFormat mediumFormatter= SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM,SimpleD ateFormat.LONG); System.out.println(shortFormatter.format(today)); System.out.println(longFormatter.format(today)); System.out.println(mediumFormatter.format(today)); String DateAsText=shortFormatter.format(today); Date TextAsDate=shortFormatter.parse(DateAsText); System.out.println(TextAsDate); } }

OUTPUT:

RESULT: Thus the program to develop a Date class was executed and the output was verified successfully.

EX: NO. 3 DATE:


AIM:

Lisp-like list in Java

To implement Lisp-like list in Java. To perform the basic operations such as 'car', 'cdr', and 'cons'. ALGORITHM: Step 1: Start the program. Step 2: Create a class LispCommands with a list in it. Step 3: Define a function parse to write the elements into the list. Step 4: Define a function car to return the leading element of the list. Step 5: Define a function cdr to return the list starting from the second element. Step 6: Define a function cons which adds an element to the front of the list. Step 7: Call the respective functions with the appropriate arguments. Step 8: Stop the program.

PROGRAM: import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Logger; public class LispCommands { private String[] tokenList; private static Logger LOGGER = Logger.getLogger(LispCommands.class.getName()); public LispCommands() { } private void car() { LOGGER.info(tokenList[0]); } private void cdr() { List<String> list = Arrays.asList(tokenList); ArrayList<String> slist = new ArrayList<String>(list); slist.remove(0); display(slist); } private void cons(String args) { List<String> arrayList = new ArrayList<String>(Arrays.asList(tokenList)); arrayList.add(args); Collections.reverse(arrayList); display(arrayList); } private void parse(String args) { ArrayList<String> tokenList = new ArrayList<String>(); if(args != null) {

StringTokenizer tokens = new StringTokenizer(args,"[]"); while (tokens.hasMoreElements()) { StringTokenizer commaTokens = new StringTokenizer(tokens.nextToken(),","); while (commaTokens.hasMoreElements()) { String token = commaTokens.nextToken(); if(token != null && !token.trim().equals("")) tokenList.add(token.trim()); } } } this.tokenList = tokenList.toArray(new String[0]); } private void display(Object result) { System.out.println(); if(result instanceof String) LOGGER.info(result.toString()); else if(result.getClass().getName().equals("java.util.ArrayList")) LOGGER.info(result.toString()); } public static void main(String[] args) { LispCommands L = new LispCommands(); L.parse("[3, 0, 2, 5]"); L.car(); L.cdr(); L.cons("7"); } }

OUTPUT:

RESULT: Thus the program to implement Lisp-like list in Java was executed and the output was verified successfully.

EX: NO. 4 DATE:


AIM:

Design a Java interface for ADT Stack

To design a Java interface for ADT Stack and to develop two different classes that implements this interface, one using array and the other using linked-list. ALGORITHM: Step 1: Start the program. Step 2: Design an interface for Stack ADT with functions push, pop and display. Step 3: Define a class to implement the stack using array. Step 4: Define the functions of the interface accordingly and handle the stack overflow and underflow exceptions. Step 5: Define a class to implement the stack using linked list. Step 6: Define the functions of the interface accordingly and handle the exceptions. Step 7: Stop the program.

PROGRAM: import java.io.*; import java.util.*; interface Mystack { public void pop(); public void push(); public void display(); } class Stack_array implements Mystack { final static int n=5; int stack[]=new int[n]; int top=-1; public void push() { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); if(top==(n-1)) { System.out.println(" Stack Overflow"); return; } else { System.out.println("Enter the element"); int ele=Integer.parseInt(br.readLine()); stack[++top]=ele; } } catch(IOException e) { System.out.println("e"); } } public void pop() { if(top<0) { System.out.println("Stack underflow"); return; } else

{ int popper=stack[top]; top--; System.out.println("Popped element:" +popper); } } public void display() { if(top<0) { System.out.println("Stack is empty"); return; } else { String str=" "; for(int i=0;i<=top;i++) str=str+" "+stack[i]+" <--"; System.out.println("Elements are:"+str); } } } class Link { public int data; public Link nextLink; public Link(int d) { data= d; nextLink=null; } public void printLink() { System.out.print(" --> "+data); } } class Stack_List implements Mystack { private Link first; public Stack_List() { first = null; } public boolean isEmpty() {

return first == null; } public void push() { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the element"); int ele=Integer.parseInt(br.readLine()); Link link = new Link(ele); link.nextLink = first; first = link; } catch(IOException e) { System.err.println(e); } } public Link delete() { Link temp = first; try { first = first.nextLink; } catch(NullPointerException e) { throw e; } return temp; } public void pop() { try { Link deletedLink = delete(); System.out.println("Popped: "+deletedLink.data); } catch(NullPointerException e) { throw e; } } public void display() {

if(first==null) System.out.println("Stack is empty"); else { Link currentLink = first; System.out.print("Elements are: "); while(currentLink != null) { currentLink.printLink(); currentLink = currentLink.nextLink; } System.out.println(""); } } } class StackADT { public static void main(String arg[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Implementation of Stack using Array"); Stack_array stk=new Stack_array(); int ch=0; do { System.out.println("1.Push 2.Pop 3.Display"); System.out.println("Enter your choice:"); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: stk.push(); break; case 2: stk.pop(); break; case 3: stk.display(); break; } }while(ch<4); System.out.println("Implementation of Stack using Linked List"); Stack_List stk1=new Stack_List(); ch=0; do

{ System.out.println("1.Push 2.Pop 3.Display"); System.out.println("Enter your choice:"); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: stk1.push(); break; case 2: try { stk1.pop(); } catch(NullPointerException e) { System.out.println("Stack underflown"); } break; case 3: stk1.display(); break; } }while(ch<4); } }

OUTPUT:

RESULT: Thus the program to implement Stack ADT using array and linked list was executed and the output was verified successfully.

EX: NO. 5 DATE:


AIM:

Design a Vehicle class hierarchy in Java

To design a Vehicle class hierarchy in Java and to demonstrate polymorphism. ALGORITHM: Step 1: Start the program. Step 2: Define a class Vehicle with fields register no. and model. Step 3: Define a method display which displays all the data fields. Step 4: Define the classes namely Twowheeler, Threewheeler and Fourwheeler as subclasses of Vehicle class. Step 5: These subclasses defines a method named display that overrides the super class method. Step 6: Create objects for the subclasses and call the appropriate methods. Step 7: Stop the program.

PROGRAM: import java.io.*; class Vehicle { String regno; int model; Vehicle(String r, int m) { regno=r; model=m; } void display() { System.out.println("Registration no: "+regno); System.out.println("Model no: "+model); } } class Twowheeler extends Vehicle { int noofwheel; Twowheeler(String r,int m,int n) { super(r,m); noofwheel=n; } void display() { System.out.println("Two wheeler tvs"); super.display(); System.out.println("No. of wheel : " +noofwheel); } } class Threewheeler extends Vehicle { int noofleaf; Threewheeler(String r,int m,int n) { super(r,m); noofleaf=n; } void display() { System.out.println("Three wheeler auto");

super.display(); System.out.println("No. of leaf:" +noofleaf); } } class Fourwheeler extends Vehicle { int noofleaf; Fourwheeler(String r,int m,int n) { super(r,m); noofleaf=n; } void display() { System.out.println("Four wheeler car"); super.display(); System.out.println("No. of leaf:" +noofleaf); } } public class Vehicledemo { public static void main(String arg[]) { Twowheeler t1; Threewheeler th1; Fourwheeler f1; t1=new Twowheeler("TN74 12345", 1,2); th1=new Threewheeler("TN74 54321", 4,3); f1=new Fourwheeler("TN34 45677",5,4); t1.display(); th1.display(); f1.display(); } }

OUTPUT:

RESULT: Thus the program to design vehicle class hierarchy and to demonstrate polymorphism was executed and the output was verified successfully.

EX: NO. 6 DATE:


AIM:

Random Generation of objects

. To design classes namely Currency, Rupee, and Dollar. To write a program that randomly generates Rupee and Dollar objects and writes them into a file using object serialization. To write another program to read that file, and to convert to Rupee if it reads a Dollar, while leave the value as it is if it reads a Rupee. ALGORITHM: Step 1: Start the programs. Step 2: Define a class Currency as an abstract class with abstract methods. Step 3: Define the classes Rupee and Dollar as subclasses of Currency. Step 4: Define the abstract methods of the super class accordingly in each subclass. Step 5: The dollar value is converted to equivalent rupee value within a method of Dollar class. Step 6: Define a class StoreCurrency that randomly generates objects of Rupee and Dollar classes. Step 7: These objects are written into a file named currency using object serialization. Step 8: Define a class ReadCurrency that reads the objects from the file currency, and displays them. Step 9: Stop the programs.

PROGRAM: Currency.java import java.io.Serializable; public abstract class Currency implements Serializable { protected static final Double DOLLAR_RUPEE_EXCHAGERATE = 44.445D; public Currency(Double money) { super(); this.money = money; } protected Double money; public abstract Double getValue (); public abstract String getPrintableValue(); } Rupee.java public class Rupee extends Currency { public Rupee(Double amount) { super(amount); } public Double getValue() { return this.money; } public String getPrintableValue() { String strValue = "Object Name : Rupee \nINR : Rs " + getValue() + "\n------------------\n"; return strValue; } } Dollar.java public class Dollar extends Currency { public Dollar(Double money) { super(money); }

public Double getValue() { return (this.money * DOLLAR_RUPEE_EXCHAGERATE); } public String getPrintableValue() { String strValue = "Object Name : Dollar \nUSD : $" + this.money + " \nINR : Rs" + getValue() + "\n------------------\n"; return strValue; } } StoreCurrency.java import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.Random; public class StoreCurrency { public static void main(String[] args) throws FileNotFoundException,IOException { Currency currency = null; ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("currency.dat"))); Random random = new Random(); for (int i = 0; i < 10; i++) { int decide = random.nextInt(); Double value = (random.nextDouble() *10); if ( (decide%2)==0 ) currency = new Rupee(value); else currency = new Dollar(value); out.writeObject(currency); } out.writeObject(null); out.close(); } }

ReadCurrency.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class ReadCurrency { public static void main(String[] args) throws IOException, ClassNotFoundException { Currency currency = null; ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("currency.dat"))); while ((currency = (Currency) in.readObject()) != null) { System.out.println(currency.getPrintableValue()); } in.close(); } }

OUTPUT:

RESULT: Thus the program to generate objects randomly and to write them into a file using object serialization was executed. The file was read and the required rupee-dollar conversions were performed and the output was verified successfully.

EXP: No. 7 DATE:


AIM:

Calculator in Java

To design a calculator using event-driven programming paradigm of Java. ALGORITHM: Step 1: Start the program. Step 2: Create a frame for the calculator and include the swing components such as buttons and text field as required in it. Step 3: Layouts such as Border Layout and Grid Layout are used to align the components as per the requirements of the calculator. Step 4: Redefine the actionPerformed() method in the ActionListener interface to perform the appropriate operations when the buttons are pressed. Step 5: Provide mechanisms to handle the Number Format exceptions that may occur. Step 6: Stop the program.

PROGRAM: import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Calculator extends JFrame { private static final Font BIGGER_FONT = new Font("monspaced", Font.PLAIN, 20); private JTextField _displayField; private boolean _startNumber = true; private String _previousOp ="="; private CalcLogic _logic = new CalcLogic(); public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception unused) { } Calculator window = new Calculator(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public Calculator() { _displayField = new JTextField("0", 12); _displayField.setHorizontalAlignment(JTextField.RIGHT); _displayField.setFont(BIGGER_FONT); JButton clearButton = new JButton("Clear"); clearButton.setFont(BIGGER_FONT); clearButton.addActionListener(new ClearListener()); ActionListener numListener = new NumListener(); String buttonOrder = "789456123 0 "; JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(5, 3, 2, 2)); for (int i = 0; i < buttonOrder.length(); i++) { String keyTop = buttonOrder.substring(i, i+1); JButton b = new JButton(keyTop); if (keyTop.equals(" ")) {

b.setEnabled(false); } else { b.addActionListener(numListener); b.setFont(BIGGER_FONT); } buttonPanel.add(b); } ActionListener opListener = new OpListener(); JPanel opPanel = new JPanel(); opPanel.setLayout(new GridLayout(5, 1, 2, 2)); String[] opOrder = {"+", "-", "*", "/", "="}; for (int i = 0; i < opOrder.length; i++) { JButton b = new JButton(opOrder[i]); b.addActionListener(opListener); b.setFont(BIGGER_FONT); opPanel.add(b); } JPanel clearPanel = new JPanel(); clearPanel.setLayout(new FlowLayout()); clearPanel.add(clearButton); JPanel content = new JPanel(); content.setLayout(new BorderLayout(5, 5)); content.add(_displayField,BorderLayout.NORTH ); content.add(buttonPanel ,BorderLayout.CENTER); content.add(opPanel ,BorderLayout.EAST ); content.add(clearPanel ,BorderLayout.SOUTH ); content.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); this.setContentPane(content); this.pack(); this.setTitle("Calculator"); this.setResizable(false); } private void actionClear() { _startNumber = true; _displayField.setText("0"); _previousOp = "="; _logic.setTotal("0"); } class OpListener implements ActionListener { public void actionPerformed(ActionEvent e) {

if (_startNumber) { actionClear(); _displayField.setText("ERROR - No operator"); } else { _startNumber = true; try { String displayText = _displayField.getText(); if (_previousOp.equals("=")) _logic.setTotal(displayText); else if (_previousOp.equals("+")) _logic.add(displayText); else if (_previousOp.equals("-")) _logic.subtract(displayText); else if (_previousOp.equals("*")) _logic.multiply(displayText); else if (_previousOp.equals("/")) _logic.divide(displayText); _displayField.setText("" + _logic.getTotalString()); } catch (NumberFormatException ex) { actionClear(); _displayField.setText("Error"); } _previousOp = e.getActionCommand(); } } } class NumListener implements ActionListener { public void actionPerformed(ActionEvent e) { String digit = e.getActionCommand(); if (_startNumber) { _displayField.setText(digit); _startNumber = false; } else { _displayField.setText(_displayField.getText() + digit); }

} } class ClearListener implements ActionListener { public void actionPerformed(ActionEvent e) { actionClear(); } } } class CalcLogic { private int _currentTotal; public CalcLogic() { _currentTotal = 0; } public String getTotalString() { return "" + _currentTotal; } public void setTotal(String n) { _currentTotal = convertToNumber(n); } public void add(String n) { _currentTotal += convertToNumber(n); } public void subtract(String n) { _currentTotal -= convertToNumber(n); } public void multiply(String n) { _currentTotal *= convertToNumber(n); } public void divide(String n) { _currentTotal /= convertToNumber(n); } private int convertToNumber(String n) { return Integer.parseInt(n); } }

OUTPUT:

RESULT: Thus the program to design a calculator was executed and the output was verified successfully.

EXP: NO. 8 DATE:


AIM:

Multithreading in Java

To write a program in Java that prints all the prime numbers in the Fibonacci series below 10000 using multithreading. ALGORITHM: Step 1: Start the program. Step 2: Create a thread called Prime Thread that stores all the prime numbers below 10000. Step 3: Create another thread called Fibonacci Thread that stores the elements of the Fibonacci series below 10000. Step 4: Prime Thread and Fibonacci Thread are assigned a higher priority than the main thread of the program. Step 5: The main thread reads the values stored by both the threads, checks for the common elements and prints them. Step 6: Stop the program.

PROGRAM: interface maxlimit { public static final int MAX_LIMIT=10000; } class prime extends Thread implements maxlimit { int num[]=new int[MAX_LIMIT]; prime(String n) { super(n); for(int i=0;i<MAX_LIMIT;i++) num[i]=-1; } public void run() { int k=0,flag; for(int i=2;i<=MAX_LIMIT;i++) { flag=0; for(int j=2;j<i;j++) { if(i%j==0) { flag=1; break; } } if(flag==0) { num[k]=i; k++; } } } } class fibonacci extends Thread implements maxlimit { int num[]=new int[MAX_LIMIT]; fibonacci(String n) { super(n); for(int i=0;i<MAX_LIMIT;i++) num[i]=-1; }

public void run() { int f1=-1,f2=1,f3=0,k=0; while(f3<=MAX_LIMIT) { f3=f1+f2; num[k]=f3; k++; f1=f2; f2=f3; } } } class primefibi { public static void main(String arg[]) { prime p=new prime("Prime Thread"); fibonacci f=new fibonacci("Fibonacci Thread"); p.setPriority(9); f.setPriority(9); p.start(); f.start(); System.out.println("Prime numbers in fibonacci series"); for(int i=0;p.num[i]!=-1;i++) { for(int j=0;f.num[j]!=-1;j++) { if(p.num[i]==f.num[j]) { System.out.println(p.num[i]); break; } } } } }

OUTPUT:

RESULT: Thus the program to print the prime numbers in the Fibonacci series using multithreading was executed and the output was verified successfully.

EXP: NO. 9 DATE:


AIM:

Simple OPAC system for library

To develop a simple OPAC system for library using event-driven and concurrent programming paradigms of Java. JDBC is used to connect to a back-end database. ALGORITHM: Step 1: Start the program. Step 2: Design the front end for the library system. Step 3: Connect the front end with the database at the backend using JDBC. Step 4: Design the front end such that it accepts the inputs from the user and inserts the records into the database. Step 5: Display the contents of the database at the front end. Step 6: Suspend the established connections. Step 7: Stop the program.

PROGRAM: Datas.java 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"); stat = conn.createStatement();

res = stat.executeQuery("Select * from stu"); res.next(); } catch(Exception e) { System.out.println("Error" +e); } 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(2)); name.setText(res.getString(3)); } catch(Exception e) { } } class WIN extends WindowAdapter { public void windowClosing(WindowEvent w) { JOptionPane jop = new JOptionPane(); jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSAG E); } } }

Prog1.java 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:co"); } catch(Exception e) { System.out.println("connection error"); } } void myput() { try { stmt=con.createStatement(); rs=stmt.executeQuery("SELECT * FROM opac"); 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[]) { Ja j=new Ja(); j.myput(); } }

OUTPUT:

RESULT: Thus the program to design a simple OPAC system for library was executed and the output was verified successfully.

EXP: NO. 10 DATE:


AIM:

Multithreaded Echo Server and Client

To develop a multithreaded echo server and a corresponding client. ALGORITHM: Step 1: Start the program. Step 2: Create a Socket at the Server side. Step 3: Design the server such that it responds to each client using a separate thread. Step 4: The server receives the data sent by the client and echoes those data. Step 5: Provide the necessary exception handling mechanisms at the server. Step 6: Create a Socket at the client side. Step 7: Get the host name from the user. Step 8: Establish a connection between the server and the client. Step 9: Transmit the data from the client side to the server. Step 10: Provide the necessary exception handling mechanisms at the client. Step 11: Stop the program.

PROGRAM: EchoServer.java import java.net.*; import java.io.*; public class EchoServer { ServerSocket m_ServerSocket; public EchoServer() { try { m_ServerSocket = new ServerSocket(12111); } catch(IOException ioe) { System.out.println("Could not create server socket at 12111. Quitting."); System.exit(-1); } System.out.println("Listening for clients....."); int id = 0; while(true) { try { Socket clientSocket = m_ServerSocket.accept(); ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++); cliThread.start(); } catch(IOException ioe) { System.out.println("Exception encountered on accept. Ignoring. Stack Trace :"); ioe.printStackTrace(); } } } public static void main (String[] args) { new EchoServer(); } class ClientServiceThread extends Thread {

Socket m_clientSocket; int m_clientID = -1; boolean m_bRunThread = true; ClientServiceThread(Socket s, int clientID) { m_clientSocket = s; m_clientID = clientID; } public void run() { BufferedReader in = null; PrintWriter out = null; System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " + m_clientSocket.getInetAddress().getHostName()); try { in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream())); out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream())); while(m_bRunThread) { String clientCommand = in.readLine(); System.out.println("Client Says :" + clientCommand); if(clientCommand.equalsIgnoreCase("quit")) { m_bRunThread = false; System.out.print("Stopping client thread for client : " + m_clientID); } else { out.println(clientCommand); out.flush(); } } } catch(Exception e) { e.printStackTrace(); } finally { try {

in.close(); out.close(); m_clientSocket.close(); System.out.println("...Stopped"); } catch(IOException ioe) { ioe.printStackTrace(); } } } } } EchoClient.java import java.net.*; import java.io.*; public class EchoClient { public static void main(String[] args) { if(args.length == 0) { System.out.println("Usage : EchoClient <serverName>"); return; } Socket s = null; try { s = new Socket(args[0], 12111); } catch(UnknownHostException uhe) { System.out.println("Unknown Host :" + args[0]); s = null; } catch(IOException ioe) { System.out.println("Cant connect to server at 12111. Make sure it is running."); s = null; } if(s == null) System.exit(-1);

BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); out.println("Hello"); out.flush(); System.out.println("Server Says : " + in.readLine()); out.println("This"); out.flush(); System.out.println("Server Says : " + in.readLine()); out.println("is"); out.flush(); System.out.println("Server Says : " + in.readLine()); out.println("a"); out.flush(); System.out.println("Server Says : " + in.readLine()); out.println("Test"); out.flush(); System.out.println("Server Says : " + in.readLine()); out.println("Quit"); out.flush(); } catch(IOException ioe) { System.out.println("Exception during communication. Server probably closed connection."); } finally { try { out.close(); in.close(); s.close(); } catch(Exception e) { e.printStackTrace(); } } } }

OUTPUT:

RESULT: Thus the program to develop a multithreaded echo server and client was executed and the output was verified successfully.

Anda mungkin juga menyukai