Vous êtes sur la page 1sur 39

SUBMITTED TO: SUBMITTED BY: Mr.

VINOD JAIN VANDANA JAIN 07/CS/103

Question 1. Write a program to create a user-defined exception called No Match exception that throws an arbitrary message when a string is not equal to India. Answer: PROGRAM: class NoMatchException extends Exception { NoMatchException(String s) { s="India"; } public String toString() { return "No Match Exception:: Strings dont match."; } } class NME { public void Match(String s) throws NoMatchException { String p="India"; if(!s.equals(p)) throw new NoMatchException(s); System.out.println("Matching Strings"); } public static void main (String a[]) { NME n= new NME(); try { n.Match(a[0]); } catch(NoMatchException e) { e.printStackTrace(); } }

OUTPUT:

Question 2a. What is multithreading? Explain the life cycle of a thread. Write a program to set priorities to three threads printing the values of a variable 1 to 5. Answer: MULTITHREADING: Multithreading allows two parts of the same program to run concurrently. Life cycle of a thread: When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states. By invoking start() method, it doesn t mean that the thread has access to CPU and start executing straight away. Several factors determine how it will proceed. Different states of a thread are: 1 1. New state After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 2 2. Runnable (Ready-to-run) state A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 3 4 3. Running state A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 5

6 7 8 9 4. Dead state A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. 10 11 5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

12 Program threads Priorities: public class Main { public void setPrioritiesOnThreads() { Thread thread1 = new Thread(new TestThread(1)); Thread thread2 = new Thread(new TestThread(2)); Thread thread3 = new Thread(new TestThread(3)); thread1.setPriority(Thread.MAX_PRIORITY); thread2.setPriority(Thread.MIN_PRIORITY); thread3.setPriority(Thread.MIN_PRIORITY); thread1.start(); thread2.start(); thread2.start(); try { thread1.join(); thread2.join(); thread2.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Done."); } public static void main(String[] args) { new Main().setPrioritiesOnThreads(); } class TestThread implements Runnable { int id; public TestThread(int id) { this.id = id; } public void run() { for (int i = 1; i <= 5; i++) { System.out.println("Thread" + id + ": " + i); } } } }

OUTPUT:

Question 2b. Differentiate between Interfaces and Abstract classes with suitable examples. Answer: INTERFACE: 1 2 3 - In interface it is necessary to implements all the methods declared in it. - It supports multiple inheritance. - Program as sown below.

Program Interface: interface shape { public void area(); public void circumference(); public void display(); } class circle implements shape { public void area() { double radius=3,area; area= radius*radius*22/7; System.out.println("area="+area); } public void circumference() { double radius=1,circumference; circumference=radius*44/7; System.out.println("circumference="+circumference); } public void display() { System.out.println("circle area and circumference"); } } public class rahul1 { public static void main(String[] args) { circle obj=new circle(); obj.display(); obj.area(); obj.circumference(); } }

OUTPUT:

ABSTRACT CLASS: 1 2 3 - In this it is not necessary to implement every method declared in it. - It supports single inheritance. - Program as shown below.

Program Abstract class: abstract class shape { public abstract void area(); //public void volume(); public void display() { System.out.println("shape"); } } class circle extends shape { public void area() { double radius=3,area; area= radius*radius*22/7; System.out.println("area="+area);

} } public class rahul2 { public static void main(String[] args) { circle obj=new circle(); obj.display(); obj.area(); } } OUTPUT:

Question 5: What is CORBA? Explain architecture of CORBA. Explain steps to implement CORBA objects.

ANS: CORBA:

CORBA lets you make calls between Java objects and objects written in other languages. CORBA depends on having an Object Request Broker (ORB) available on both client and server. CORBA is a standard defined by Object Management Group that enables software components written in multiple computer languages and running on multiple computers to work together. ORB as a kind of universal translator for inter-object CORBA communication. The CORBA 2 specification defines more than a dozen "services" that the ORB can use for various kinds of housekeeping tasks. These range from a "startup service" to get the process going, to a "life cycle service" that you use to create, copy, move, or destroy objects, to a "naming service" that allows you to search for objects if you know their name.

(Client) main ( )

(Server) main ( )

Object Reference Stub code

Object Implementation Skeleton

Object Request Broker

Network

Object Request Broker

Steps for implementing CORBA objects:

1. Write the interface that specifies how the object works; using IDL, the interface definition language for defining CORBA interfaces. IDL is a special language to specify interfaces in a language-neutral form.

2. Using the IDL compiler(s) for the target language(s), generate the needed stub and helper classes.

3. Add the implementation code for the server objects, using the language of your choice. (The skeleton created by the IDL compiler is only glue code. You still need to provide the actual implementation code for the server methods.) Compile the implementation code.

4. Write a server program that creates and registers the server objects. The most convenient method for registration is to use the CORBA naming service, a service that is similar to the rmiregistry.

5. Write a client program that locates the server objects and invokes services on them.

6. Start the naming service and the server program on the server, and start the client program on the client. These steps are quite similar to the steps that you use to build distributed applications with RMI, but with two important differences:

You can use any language with a CORBA binding to implement clients and servers.

You use IDL to specify interfaces.

QUES 8: Write short notes on a) Digital signature b) Bytecode verification

ANS a: Digital signature:

* Digital signature is a signature used in email or in any internet application. * It is created by Message digests.

* A message digest is a digital finger print of a block of data.

A message digest has two essential properties:

1. If one bit or several bits of the data are changed, then message digest also change. 2. A forger who is possession of a given message cannot construct a fake message that has the same message digest as the original. A message is used to avoid transmitting a password in clear text from a client to a server. A message digest takes an arbitrary amount of input data and produces a short, digested version of the data. Java Cryptography Architecture (JCA) makes it easy to use message digests. The java.security.Message Digest class encapsulates a cryptographic message digest.

Java.security.MessageDigest

MessageDigest md = MessageDigest.getInstance(SHA-1); //supply input md.update(byteArray); //create message digest Byte [] mdcode = md.digest(); The message digest object is automatically reset after this call.

SIGNATURES: A signature provides two security services, authentication and integrity. A signature is a message digest that is encrypted with the signer's private key. Only the signer's public key can decrypt the signature, which provides authentication. If the message digest of the message matches the decrypted message digest from the signature, then integrity is assured. Java Security API class, java.security.Signature represents cryptographic signatures.

The basic procedure is very similar to the password based. The client generates a timestamp and a random number. The client creates a signature of this data and sends it to the server. The server can verify the signature with the client's public key.

DIGITAL SIGNING:

Sender signs with private key Signature rsa = Signature.getInstance(RSA); //initialize with private key PrivateKey privateKey = myKeyPair.getPrivate(); rsa.initSign(privateKey); //update the signature object with the data to be signed rsa.update(someData); //sign the data byte[] signature = rsa.sign();

DIGITAL VERIFICATION:

Receiver verifies data with public key PublicKey pubKey = aKeyPair.getPublic(); rsa.initVerify(pubKey); //update the signature object with the data to be verified rsa.update(data); //verify the signature Boolean isVerified = rsa.verify(sig);

LIMITATIONS WITH SIGNATURES:

Signatures do not provide confidentiality. A signature accompanies a plain text message. Anyone can intercept and read the message. Creating and maintaining the public key database is difficult. The server needs to obtain these public keys in a secure way. Certificates solve this problem

ANS 8b: BYTECODE VERIFICATION:

The bytecode verifier traverses the bytecodes, constructs the type state information, and verifies the types of the parameters to all the bytecode instructions. Once the verifier is done, a number of important properties are known: There are no operand stack overflows or underflows. The types of the parameters of all bytecode instructions are known to always be correct Object field accesses are known to be legal--private, public, or protected

While all this checking appears excruciatingly detailed, by the time the bytecode verifier has done its work, the Java interpreter can proceed, knowing that the code will run securely.

When a class loader presents the bytecodes of a newly loaded java platform class to the virtual machine, these bytecodes are first inspected by a verifier. The verifier checks that the instructions cannot perform actions that are obviously damaging. All classes excepts system classes are verified. We can deactivate verification by no verify option.

For example

Java noverify Hello QUES 7: Write an application to implement table and process indicators.

ANS: TABLES:

The JTable component displays a two-dimensional grid of objects. Of course, tables are common in user interfaces. The Swing team has put a lot of effort into the table control. Tables are inherently complex, butperhaps more successfully than with other Swing classes the JTable component hides much of that complexity. You can produce fully functional tables with rich behavior by writing a few lines of code. Of course,You can write more code and customize the display and behavior for your specific applications. In this section, we explain how to make simple tables, how the user interacts with them, and how to make some of the most common adjustments. As with the other complex Swing controls, it is impossible to cover all aspects in complete detail. For more information, look in Graphic Java 2 by David Geary or Core Java Foundation Classes by Kim Topley.

A Simple Table:

As with the tree control, a JTable does not store its own data but obtains its data from a table model. The JTable class has a constructor that wraps a two-dimensional array of objects into a default model.

A simple table Example:

Program for table implementation:

import java.awt.*; import javax.swing.*; import javax.swing.table.*; /* <applet code="table.class" width="200" height="200"> </applet>*/ public class table extends JApplet { public void init() { Container cp=getContentPane(); cp.setLayout(new BorderLayout()); String colHeads[] = { "rollno","name"};

String data[][]={ {"1001","vandana",}, {"1002","sunder",}, {"1003","neha",}, {"1004","sandhya",},}; JTable table=new JTable(data,colHeads); int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp=new JScrollPane(table,v,h); cp.add(jsp); } }

OUTPUT:

PROGRESS INDICATORS:

In the following sections, we discuss three classes for indicating the progress of a slow activity. A JProgressBar is a Swing component that indicates progress. A progress Monitor is a dialog box that contains a progress bar. A Progress Monitor Input Stream displays a progress monitor dialog box while the stream is read. PROGRESS BARS

A progress bar is a simple component just a rectangle that is partially filled with color to indicate the progress of an operation. By default, progress is indicated by a string "n%". You can see a progress bar in

You construct a progress bar much as you construct a slider, by supplying the minimum and maximum value and an optional orientation: progressBar = new JProgressBar(0, 1000); progressBar = new JProgressBar(SwingConstants.VERTICAL, 0, 1000); You can also set the minimum and maximum with the setMinimum and setMaximum methods. Unlike a slider, the progress bar cannot be adjusted by the user. Your program needs to call setValue to update it. If you call progressBar.setStringPainted(true); The progress bar computes the completion percentage and displays a string "n%". If you want to show a different string, you can supply it with the setString method: if (progressBar.getValue() > 900) progressBar.setString("Almost Done"); The program in Example 6-16 shows a progress bar that monitors a simulated time-consuming activity. The Simulated Activity class implements a thread that increments a value current 10 times per second. When it reaches a target value, the thread finishes. To terminate the thread before it has reached its target, you interrupt it.

Program for JProgressBar implementation:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

import javax.swing.text.html.*; class SwingProgressBar { final static int interval = 1000; int i; JLabel label; JProgressBar pb; Timer timer; JButton button; public SwingProgressBar() { JFrame frame = new JFrame("Swing Progress Bar"); button = new JButton("Start"); button.addActionListener(new ButtonListener()); pb = new JProgressBar(0, 20); pb.setValue(0); pb.setStringPainted(true); label = new JLabel("Roseindia.net"); JPanel panel = new JPanel(); panel.add(button); panel.add(pb); JPanel panel1 = new JPanel(); panel1.setLayout(new BorderLayout()); panel1.add(panel, BorderLayout.NORTH); panel1.add(label, BorderLayout.CENTER); panel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); frame.setContentPane(panel1); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create a timer. timer = new Timer(interval, new ActionListener() { public void actionPerformed(ActionEvent evt) { if (i == 20){ Toolkit.getDefaultToolkit().beep(); timer.stop(); button.setEnabled(true); pb.setValue(0); String str = "<html>" + "<font color=\"#FF0000\">" + "<b>" + "Downloading completed." + "</b>" + "</font>" + "</html>"; label.setText(str); } i = i + 1; pb.setValue(i); } }); }

class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae) { button.setEnabled(false); i = 0; String str = "<html>" + "<font color=\"#008000\">" + "<b>" + "Downloading is in process......." + "</b>" + "</font>" + "</html>"; label.setText(str); timer.start(); } } public static void main(String[] args) {

SwingProgressBar spb = new SwingProgressBar(); } }

OUTPUT:

QUES 6a. What r AWT components. How images r manipulated using awt components? b. What r beans? Explain bean writing process in detail with the help of an example.

ANS a: Abstract Windows Toolkit(AWT):

Abstract windows toolkit contains all the classes for creating user interfaces and for painting graphics and images.

A user interface object such as button or a scrollbar is called in AWT terminology, a component. Component class is the root of all AWT components.

The different component classes are :

Button Label TextField CheckBox ComboBox GridLayout TextArea ScrollBar

IMAGE MANIPULATION: Suppose you have an image and you would like to improve its appearance. You then need to access the individual pixels of the image and replace them with other pixels. Or perhaps you want to compute the pixels of an image from scratch, for example, to show the result of physical measurements or a mathematical computation. The BufferedImage class gives you control over the pixels in an image, and classes that implement the BufferedImageOp interface let you transform images. This is a major change from the image support in JDK 1.0. At that time, the image classes were optimized to support incremental rendering. The original purpose of the classes was to render GIF and JPEG images that are downloaded from the Web, a scan line at a time, as soon as partial image data is available. In fact, scan lines can be interlaced, with all even scan lines coming first, followed by the odd scan lines. That mechanism lets a browser quickly display an approximation of the image while fetching the remainder of the image data. The ImageProducer, ImageFilter, and ImageConsumer interfaces in JDK 1.0 expose all the complexities of incremental rendering. Writing an image manipulation that fit well into that framework was quite complex. Fortunately, the need for using these classes has completely gone away. JDK 1.2 replaced the "push model" of JDK 1.0 with a "direct" model that lets you access pixels directly and conveniently. We cover only the direct model in this chapter. The only disadvantage of the direct model is that it requires all image pixels to be in memory. (In practice, the "push model" had the same restriction. It would have required fiendish cunning to write image manipulation algorithms that processed pixels as they became available. Most users of the old model simply buffered the entire image before processing it.) Future versions of the Java platform may support a "pull" model with which a processing pipeline can reduce memory consumption and increase speed by fetching and processing pixels only when they are actually needed. Accessing Image Data

Most of the images that you manipulate are simply read in from an image file they were either produced by a device such as a digital camera or scanner, or constructed by a drawing program. In this section, we show you a different technique for constructing an image, namely, to build up an image a pixel at a time. To create an image, construct a BufferedImage object in the usual way. image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Now, call the getraster method to obtain an object of type WritableRaster. You use this object to access and modify the pixels of the image. WritableRaster raster = image.getRaster(); The setPixel method lets you set an individual pixel. The complexity here is that you can't simply set the pixel to a Color value. You must know how the buffered image specifies color values. That depends on the type of the image. If your image has a type of TYPE_INT_ARGB, then each pixel is described by four values, for red, green, blue, and alpha, each of which is between 0 and 255. You supply them in an array of four integers. int[] black = { 0, 0, 0, 255 }; raster.setPixel(i, j, black); In the lingo of the Java 2D API, these values are called the sample values of the pixel. Example For Image: Import java.awt.*; Import java.applet.*; Public class abc extends Applet { Image img; Public void init( ) { URL base; Base=getDocumentBase(); img=getImage(base,c:\abc.gif); } Public void paint(Graphics g) { WritableRaster raster=img.getRaster(); Raster.setPixel(20,20,Black); g.drawImage(img,50,70,this); } }

ANS 6b: BEANS: A java Bean is a software component that has been designed to be reusable in a variety of different environment. Example: button on a graphical user interface, spell checker.

Advantages of java beans: 1) 2) 3) Java beans are reusable. It takes benefits of write once run anywhere paradigm. The properties, events & methods of beans are exposed to application builder tool(BDK).

4) A bean may register to receive events from other objects and can generate events that are sent to other objects. Bean Development Kit: It is a Bean application builder tool.It is used to create ,configure and use the beans.

Starting BDK: First install BDK and go to path c:\bdk\beanbox directory, execute the batch file run.bat there. It will open a window where there are three main components are toolbox,beanbox and properties bean box.

The Bean-Writing Process:

Steps to create a new bean are as follows:

Step 1: Create a directory for new bean Step 2: Create the java source file. Step 3: Compile the java source file Step 4: Create a manifest file. Step 5: Generate a jar file. Step 6: Start the BDK.

Step 7: Test.

Example for Bean writing process:

Step 1: create a directory such as c:\bdk\demo\text

Step 2: Create bean source file as plaintext.java As below Import java.awt.*; Import javax.swing.JLabel; Public class plaintext extends JLabel { Public plaintext() { setText(Hello world); setOpaque(true); setBackground(Color.RED); setForeground(Color.YELLOW); setVerticalAlignment(CENTER); setHorizontalAlignment(CENTER); } }

Step 3: compile the plaintext.java and store in text directory.

Step 4:

Create a manifest plaintext.mft and store the data below Name:text/plaintext.class Java-Bean:True Menifest file identifies the bean file inside the jar file.

Step 5: Create jar file as below Jar cfm jars\text.jar plaintext.mft text\*.class.

Step 6: Start the BDK As below C:\bdk\beanbox>run.bat

Step 7: Test the bean by opening inside bdk.

QUES 4a.Write a fn. to create a database connect and retrieve all the records from a table that has name=rahul. b. What is JDBC? Explain different JDBC drivers. Explain steps of java to database communication in details.

ANS 4a: PROGRAM: import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JDBCDriverInformation { static String userid=scott, password = tiger; static String url = jdbc:odbc:bob; static Connection con = null; public static void main(String[] args) throws Exception { try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); } catch(java.lang.ClassNotFoundException e) { System.err.print(ClassNotFoundException: );

System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } Statement st=con.createStatement(); st.executeUpdate(CREATE TABLE RAHUL(NAME VARCHAR2(20),AGE INTEGER); st.executeUpdate(INSERT INTO RAHUL(VALUES (RAM,22)); ResultSet rs = st.executeQuery(SELECT * FROM RAHUL); While(rs.next()) { System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); } } }

ANS 4b:

Goal Of JDBC Is To Make Possible The Following:

Programmers can write applications in the Java programming language to access any database, using standard SQL statements or even specialized extensions of SQL while still following Java language conventions. Database vendors and database tool vendors can supply the low-level drivers. Thus, they can optimize their drivers for their specific products.

Diagram for JDBC to database Communication path:

JDBC DRIVER TYPES:

JDBC drivers are classified into the following types:

A type 1 driver translates JDBC to ODBC and relies on an ODBC driver to communicate with the database. Sun includes one such driver, the JDBC/ODBC bridge, with the JDK. However, the bridge requires deployment and proper configuration of an ODBC driver. When JDBC was first released, the bridge was handy for testing, but it was never intended for production use. At this point, plenty of better drivers are available, and we advise against using the JDBC/ODBC bridge. A type 2 driver is written partly in Java and partly in native code; it communicates with the client API of a database. When you use such a driver, you must install some platform-specific code in addition to a Java library.

A type 3 driver is a pure Java client library that uses a database-independent protocol to communicate database requests to a server component, which then translates the requests into a database-specific protocol. This can simplify deployment since the database-dependent code is located only on the server.

A type 4 driver is a pure Java library that translates JDBC requests directly to a database-specific protocol. Most database vendors supply either a type 3 or type 4 driver with their database. Furthermore, a number of third-party companies specialize in producing drivers with better standards conformance, support for more platforms, better performance, or, in some cases, simply better reliability than the drivers that are provided by the database vendors.

Basic JDBC Programming concepts: Java Database Connectivity Steps: Before you can create a java jdbc connection to the database, you must first import the java.sql package. import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be imported. 1. Loading a database driver, In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used. The return type of the Class.forName (String ClassName) method is Class. Class is a class in java.lang package. try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Or any other driver } catch(Exception x){ System.out.println( Unable to load the driver class! ); } 2. Creating a oracle jdbc Connection The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.

JDBC URL Syntax::

jdbc: <subprotocol>: <subname>

JDBC URL Example:: jdbc: <subprotocol>: <subname>Each driver has its own subprotocol Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver. try{ Connection dbConnection=DriverManager.getConnection(url,loginName,Password) } catch( SQLException x ){ System.out.println( Couldnt get connection! ); } 3. Creating a jdbc Statement object,

Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method. Statement statement = dbConnection.createStatement(); A statement object is used to send and execute SQL statements to a database. Three kinds of Statements Statement: Execute simple sql queries without parameters. Statement createStatement() Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters. PreparedStatement prepareStatement(String sql) returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements.

Callable Statement: Execute a call to a database stored procedure. CallableStatement prepareCall(String sql) returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements. 4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet. Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement class has three methods for executing statements:

executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all examples of DDL statements and are executed with the method executeUpdate. execute() executes an SQL statement that is written as String object.

ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results.

ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.

QUES 3: With reference to sockets, explain how client/server communication is accomplished in java.WAP to print the protocol,port,host and file components of a URL.

ANS: Introduction to networking:

Network is the interconnected collection of computers. In java networking is implemented by java.net.* package. All classes of networking must include the above package. Networking uses Socket and ServerSocket classes.

Connecting to a server:

Diagrammatically it can be shown as below

Program for connecting to server:

/* This program describes receiving of messages from server computer */

SocketTest.java

import java.io.*; import java.net.*; import java.util.*;

public class SocketTest { public static void main(String[] args) { char ch; try { Socket s = new Socket ("IP Address", Portno); InputStream inStream = s.getInputStream();

Scanner in = new Scanner(inStream); while (in.hasNextLine()) { String line = in.nextLine(); System.out.println(line); } } finally { s.close(); } catch (IOException e) { e.printStackTrace(); } } }

Implementing Server:

A simple server that can send information to clients. Once you start the server program, it waits for some client to attach to its port. We chose port number 8189, which is not used by any of the standard services. Program for Implementing Server:

/* This program describe sending message to client

EchoServer.java

import java.io.*;

import java.net.*; import java.util.*; public class EchoServer { public static void main(String[] args ) { try { // establish server socket ServerSocket s = new ServerSocket(8189); // wait for client connection Socket incoming = s.accept( ); try { InputStream inStream = incoming.getInputStream(); OutputStream outStream = incoming.getOutputStream(); Scanner in = new Scanner(inStream); PrintWriter out = new PrintWriter(outStream, true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); // echo client input boolean done = false; while (!done && in.hasNextLine()) { String line = in.nextLine(); out.println("Echo: " + line); if (line.trim().equals("BYE")) done = true; } }

finally { incoming.close(); } } catch (IOException e) { e.printStackTrace(); } } } To try it out, compile and run the program. Then, use telnet to connect to the following server and port: Server: 127.0.0.1 Port: 8189 The IP address 127.0.0.1 is a special address, the local loopback address, that denotes the local machine. Because you are running the echo server locally, that is where you want to connect.

Program for URL Connection:

import java.net.*; import java.io.* ; import java.util.* ; class URLdemo { public static void main(String args[ ]) throws Exception { int i ; URL u = new URL(http://www.yahoo.com:80/index.html); System.out.println(protocol name + u.getProtocol( ) );

System.out.println(Host name + u.getHost( ) ); System.out.println(port name + u.getPort( ) ); System.out.println(file name + u.getFile( ) ); URLConnection uc=u.openConnection( ); System.out.println(content type + uc.getContentType( ) ); System.out.println(content length + uc.getContentLength( ) ); System.out.println(last modified date + new Date(uc.getLastModified( ) ); System.out.println(The file contents ); InputStream is=uc.getInputStream9 ); while( I = is.read( ) ! = -1) System.out.println( (char) i ); }}

Vous aimerez peut-être aussi