Lecture 2. Basic Java Syntax by jianghongl

VIEWS: 3 PAGES: 82

									                          Java Programming




         Lecture 8.
Java Distributed Computing

        Cheng-Chia Chen




                          Transparency No. 1-1
                                             Java Networking
    Distributed Computing
   Network programming
   JDBC
   Servlets & JSPs
   Remote Method Invocation (RMI)
   Others not covered:
    CORBA
    Enterprise JavaBeans (EJB)
    JINI
    JavaSpaces




                                     Transparency No. 1-2
                                                      Java Networking
  Network programming
 Historically error-prone, difficult, complex
 but network programming in java is rather easy
  IO stream library works quite well for TCP/IP.
  Threading is also very useful and relatively easy here
 References:
  The java tutorial, Trail: Custom Networking
   http://java.sun.com/docs/books/tutorial/index.html
  Thinking in java, ch 15
   http://www.eckelobjects.com/TIJ2/index.html.
   “Java Network Programming” by Elliotte Rusty Harold,
   O’Reilly Books, 2nd Edition 2000. visit
   http://www.ibooks.com for a free online reference.


                                              Transparency No. 1-3
                                                             Java Networking
   Networking Basics
 TCP/IP Network Protocol

                       (Peer to Peer) Protocol


                            interfaces




                           InterNet
     physical layer                              physical layer




                                                     Transparency No. 1-4
                                                        Java Networking
   TCP and UDP
 TCP (Transmission Control Protocol) is a connection-based
  protocol that provides a reliable flow of data between two
  computers.
 UDP (User Datagram Protocol) is a protocol that sends
  independent packets of data, called datagrams, from one
  computer to another with no guarantees about arrival. UDP is
  not connection-based like TCP.




                                                Transparency No. 1-5
                                                           Java Networking
   Identifying a Machine
 Uniquely identify a machine from all the others in the world
 IP (Internet Protocol) address that can exist in two forms:
   DNS (Domain Name System) form: xml.cs.nccu.edu.tw
   “Dotted quad” (IP) form: 140.119.162.230
 Represented internally by 32-bit number (4 bytes)
   4.3 billion possibilities.
   IPV6 : 128-bit coming…
 static InetAddress.getByName(String) produces Java object
  containing address




                                                   Transparency No. 1-6
                                                                  Java Networking
    Servers & Clients
 Two machines must connect
 Server waits around for connection
 Client initiates connection
 Once the connection is made, server & client look
  identical
 Both ends are turned into InputStream and
  OutputStream objects, which can then be converted
  to Reader and Writer objects
                      InputStream      OutputStream

             Client   OutputStream      InputStream   server

                                                                    Socket
                          connection (full duplex)
                                                          Transparency No. 1-7
                                                               Java Networking
   Testing w/o a Network
 Here, we have no network
   Also, you may not trust your program enough yet.
 “localhost”: the “local loopback” IP address for testing
  without a network
      InetAddress addr = InetAddress.getByName(null);
 Equivalently:
      InetAddress.getByName("localhost");
 Or using the reserved IP number for the loopback:
      InetAddress.getByName("127.0.0.1");




                                                       Transparency No. 1-8
                                                          Java Networking
   WhoAmI
// Finds out your network address when
// you're connected to the Internet.
import java.net.*;
public class WhoAmI {
   public static void main(String[] args) throws Exception {
    if(args.length != 1) {
         System.err.println( "Usage: WhoAmI MachineName");
         System.exit(1);
     }
     InetAddress a = InetAddress.getByName(args[0]);
     System.out.println(a);
 }}
                                                  Transparency No. 1-9
                                                          Java Networking
    Port: Unique “Place” in a Machine
 IP address isn‟t enough to identify a unique server
 Many servers can exist on one machine
 IP machines also contain port numbers
 When you set up client and server, you must specify IP address
  and port, so they can find each other
 Not a physical location, but a software abstraction to represent
  a service
 There are 65536 ports
   in a machine
    0-1023 reserved, others usable
    80  HTTP; 110  POP3;
    20,21  ftp; 25  smtp;
    23  telnet, 119  nntp …

                                                  Transparency No. 1-10
                                                                  Java Networking
   Sockets
 Software abstraction used to represent the “terminals” of a
  connection between two machines
 Java provides a class abstraction : java.io.Socket
 Socket is the actual 2-way connector. Can initiate a connection
  with a server
 ServerSocket isn‟t really a socket but more of a
  “ServerConnector” that produces a Socket as the return value
  of accept( ), which waits for a connection.
 In the end, you get a Socket on each machine
                          InputStream      OutputStream
                 Client   OutputStream      InputStream     server

                                                                              Socket
                              connection (full duplex)
                                                          Transparency No. 1-11
                                                          Java Networking
   Just Like Files...
 Once you have a Socket, you call
  getInputStream( ) and getOutputStream( ) to produce the
  corresponding InputStream and OutputStream objects
 You convert these to readers and writers, wrap them in a
  BufferedReader or BufferedWriter and PrintWriter
 From then on, it‟s like reading and writing any other IO stream!




                                                  Transparency No. 1-12
                                                           Java Networking
   Simple Server & Client
//: Very simple server that just echoes whatever the client sends.
import java.io.*;
import java.net.*;
public class JabberServer {
 // Choose a port outside of the range 0-1023:
  public static final int PORT = 8080;
  public static void main(String args[]) throws IOException {
    ServerSocket s = new ServerSocket(PORT);
    System.out.println("Started: " + s);



                                                   Transparency No. 1-13
                                                          Java Networking



try { // Blocks until a connection occurs:
  Socket socket = s.accept();
  try {
     System.out.println( "Connection accepted: "+ socket);
     BufferedReader in = new BufferedReader(
            new InputStreamReader( socket.getInputStream()));
      // Output is automatically flushed by PrintWriter:
     PrintWriter out = new PrintWriter(
                           new BufferedWriter(
                             new OutputStreamWriter
                                 ( socket.getOutputStream())),true);

                                                  Transparency No. 1-14
                                                             Java Networking



           while (true) { // main server response
             String str = in.readLine();
             if (str.equals("END")) break;
            System.out.println("Echoing: " + str);
            out.println(str);
            }
        // Always close the two sockets...
     } finally {
       System.out.println("closing...");
        socket.close(); }
     } finally { s.close(); }
}}
                                                     Transparency No. 1-15
                                                                     Java Networking
    The client program
// Thinking in Java c15, JabberClient.java
// Very simple client that just sends lines to the server and reads lines
// that the server sends.
import java.net.*;
import java.io.*;
public class JabberClient {
       public static void main(String args[]) throws IOException {
  // "Local Loopback" IP address:
  InetAddress addr = InetAddress.getByName(null);
  System.out.println("addr = " + addr);
 // Unlike ServerSocket, client needn‟t specify its local port, which is allocated
     dynamically by machine.
  Socket socket = new Socket(addr, JabberServer.PORT);
  // Guard everything in a try-finally to make sure that the socket is closed:

                                                             Transparency No. 1-16
                                                                       Java Networking


try { System.out.println("socket = " + socket);
       BufferedReader in = new BufferedReader( new InputStreamReader(
                                   socket.getInputStream()));
      // Output is automatically flushed by PrintWriter:
       PrintWriter out = new PrintWriter( new BufferedWriter(
                  new OutputStreamWriter (socket.getOutputStream() ) ), true);

        for(int i = 0; i < 10; i ++) {
          out.println(“sending " + i);      String str = in.readLine();
          System.out.println(str);
        }
        out.println("END");
      } finally { System.out.println("closing...");       socket.close();}
} }

                                                               Transparency No. 1-17
                                                                    Java Networking
  Serving Multiple Clients via Threads
// A server that uses multithreading to handle any number of clients.
import java.io.*;        import java.net.*;
class ServeOneJabber extends Thread {
  private Socket socket; private BufferedReader in;
  private PrintWriter out;
  public ServeOneJabber(Socket s) throws IOException {
    socket = s;        in = new BufferedReader( new InputStreamReader
                                                  (socket.getInputStream()));
    // Enable auto-flush:
    out = new PrintWriter(new BufferedWriter( new OutputStreamWriter
                               ( socket.getOutputStream())), true);
    // If any of the above calls throw an exception, the caller is responsible
   // for closing the socket. Otherwise the thread will close it.
 }

                                                            Transparency No. 1-18
                                                              Java Networking



public void run() {
     try {
       while (true) {
         String str = in.readLine();
         if (str.equals("END")) break;
         System.out.println("Echoing: " + str);
         out.println(str);
       }
       System.out.println("closing...");
     } catch (IOException e) { }
       finally { try {socket.close(); } catch(IOException e) {} }
 } }
                                                      Transparency No. 1-19
                                                                          Java Networking
     MultiJabberServer
public class MultiJabberServer { static final int PORT = 8080;
   public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(PORT);
    System.out.println("Server Started");
    try {
      while(true) {
        // wait for a connection established:
        Socket socket = s.accept();
        try { new ServeOneJabber(socket).start(); }
        catch(IOException e) {
          // If it fails, close the socket, otherwise the thread will close it:
          socket.close(); }
        }
       } finally { s.close(); }
   } }
                                                                  Transparency No. 1-20
                                                                       Java Networking
    JabberClientThread
// Client that tests the MultiJabberServer by starting up multiple clients.
   import java.net.*; import java.io.*;
   class JabberClientThread extends Thread {
    private Socket socket;          private BufferedReader in;
    private PrintWriter out;        private static int counter = 0;
    private int id = counter++; private static int threadcount = 0;
    public static int threadCount() { return threadcount; }
    public JabberClientThread(InetAddress addr) {
      System.out.println("Making client " + id);
      threadcount++;
      try { socket = new Socket(addr, MultiJabberServer.PORT);
      } catch(IOException e) {
        // If the creation of the socket fails, nothing needs to be cleaned up.
      }

                                                               Transparency No. 1-21
                                                                 Java Networking


try { in = new BufferedReader( new InputStreamReader
                                               ( socket.getInputStream()));
     // Enable auto-flush:
     out = new PrintWriter( new BufferedWriter(
                new OutputStreamWriter( socket.getOutputStream())), true);
     start();
   } catch(IOException e) {
     // The socket should be closed on any failures other than the socket
     // constructor:
     try { socket.close(); } catch(IOException e2) {}
   }
   // Otherwise the socket will be closed by
   // the run() method of the thread.
 }

                                                         Transparency No. 1-22
                                                          Java Networking


public void run() {
    try {
      for(int i = 0; i < 25; i++) {
        out.println("Client " + id + ": " + i);
        String str = in.readLine();
        System.out.println(str);
      }
      out.println("END");
    }
    catch(IOException e) {}
    finally { // Always close it:
                try { socket.close();}
                catch(IOException e) {}
      threadcount--; // Ending this thread
    } } }
                                                  Transparency No. 1-23
                                                            Java Networking
   MultiJabberClient
public class MultiJabberClient {
   static final int MAX_THREADS = 40;
   public static void main(String[] args)
      throws IOException, InterruptedException {
    InetAddress addr =
      InetAddress.getByName(null);
    while(true) {
      if(JabberClientThread.threadCount() < MAX_THREADS)
        new JabberClientThread(addr);
      Thread.currentThread().sleep(100); // Why not just sleep(100)?
    } } }
                                                    Transparency No. 1-24
                                                 Java Networking
   Port Warning

 Problem: program works fine, except when client is
  behind a firewall
 Firewall doesn‟t like to see anything but ordinary
  network connections to WWW server via its standard
  http port 80
 Servlets solve the problem




                                         Transparency No. 1-25
                                                         Java Networking
   User Datagram Protocol (UDP)

 Previous examples used Transmission Control Protocol
  (TCP).
  Very high reliability, message will always get there.
  Also high overhead
 User Datagram Protocol (UDP) is an unreliable protocol
  which is much faster, but the messages won‟t always
  get there
 c.f.:
  TCP  Telephone system
  UDP  postal service

                                                 Transparency No. 1-26
                                                   Java Networking
   Datagrams

 You make your own packets and write the address on
  the outside, send it
 Based on packet contents, recipients decide whether
  they got everything, sends a message if they didn‟t, and
  you retransmit in that case.
 Reliability must be enforced by your program, not by
  the UDP protocol
 Java APIs provided in two classes:
  java.net.DatagramPacket
  java.net.DatagramSocket

                                           Transparency No. 1-27
                                                                  Java Networking
   DatagramPacket
 Encapsulation of data(packet) to be received/transmitted and
  related information.
 Constructors:
    // for receiving packets
   DatagramPacket(byte[] data [ [, int offset] , int length])
   // for sending packets
   DatagramPacket(byte[] data [ [, int offset], int length],
                                         InetAddress ia ,int port )




                                                          Transparency No. 1-28
                                                                 Java Networking
    DatagramPacket Methods
InetAddress getAddress()
         Returns the IP address of the peer machine.
 byte[] getData() Returns the data buffer.
 int getLength()      Returns the length of the data.
 int getOffset()      Returns the offset of the data to be sent/received.
 int getPort()       Returns the port number on the remote host.
 SocketAddress getSocketAddress()
         Gets the SocketAddress (usually IP address + port number) of the
   remote host.
 void setAddress(InetAddress iaddr)
 void setData(byte[] buf [, int offset, int length])
 void setLength(int length)
 void setPort(int iport)
void setSocketAddress(SocketAddress )

                                                         Transparency No. 1-29
                                                                  Java Networking
   DatagramSocket
 represents a socket for sending and receiving datagram packets
 Constructor
   // bind to local IP laddr and port port or local SocketAddr bindaddr
   // info not given => allocated by machine
   DatagramSocket([ int port [,InetAddress laddr]]
   DatagramSocket(SocketAddress bindaddr )
 Methods
   // for local info manipulation
   void bind(SocketAddress),
   isBound(),
   getLocalAddress(), getLocalPort(), getLocalSocketAddress()



                                                          Transparency No. 1-30
                                                              Java Networking



 // for remote info manipulation
   // dedicated to this remote socket address only
   connect(InetAddress, int), connect(SocketAddress),
   disconnect(),
   isConnected() : // return null/-1 if not connected.
   getInetAddress(), getPort(), getRemoteSocketAddress()
 //send/receive data
   send(DatagramPacket)
   receive(DatagramPacket)
 // others
   isClosed()
   getBroadcast(), setBroadcast(boolean),
    getSoTimeout(), setSoTimeout(int),…
                                                      Transparency No. 1-31
                                                       Java Networking
Example UDP programming: The client side program




                                               Transparency No. 1-32
                                                                       Java Networking

// Fig. 18.7: Client.java
// Client that sends and receives packets to/from a server.
  import java.io.*;    import java.net.*; import java.awt.*;
  import java.awt.event.*; import javax.swing.*;

public class Client extends JFrame {
private JTextField enterField; private JTextArea displayArea;
private DatagramSocket socket;

// set up GUI and DatagramSocket
public Client()
{ super( "Client" );
   Container container = getContentPane();
   enterField = new JTextField( "Type message here" );
   enterField.addActionListener(
    new ActionListener() {
       public void actionPerformed( ActionEvent event )
       {                                                       Transparency No. 1-33
         // create and send packet                                         Java Networking

 try {
displayArea.append( "\nSending packet containing: " + event.getActionCommand() + "\n" );

   // get message from textfield and convert to byte array
   String message = event.getActionCommand();
   byte data[] = message.getBytes();
   // create sendPacket
   DatagramPacket sendPacket = new DatagramPacket( data,
             data.length, InetAddress.getLocalHost(), 5000 );
   socket.send( sendPacket ); // send packet
   displayArea.append( "Packet sent\n" );
  displayArea.setCaretPosition( displayArea.getText().length() );
 } // process problems creating or sending packet
 catch ( IOException ioException ) { displayMessage( ioException.toString() + "\n" );
              ioException.printStackTrace();           }


                                                                   Transparency No. 1-34
                                                                  Java Networking
      } // end actionPerformed
   } // end inner class
); // end call to addActionListener
container.add( enterField, BorderLayout.NORTH );
displayArea = new JTextArea();
container.add( new JScrollPane( displayArea ), BorderLayout.CENTER );
setSize( 400, 300 );        setVisible( true );
// create DatagramSocket for sending and receiving packets
try {
 socket = new DatagramSocket();
}
// catch problems creating DatagramSocket
catch( SocketException socketException ) {
   socketException.printStackTrace();
   System.exit( 1 );
}

                                                          Transparency No. 1-35
                                                                      Java Networking
} // end Client constructor
 // wait for packets to arrive from Server, display packet contents
 private void waitForPackets()
 { while ( true ) { // loop forever
      // receive packet and display contents
      try { // set up packet
         byte data[] = new byte[ 100 ];
         DatagramPacket receivePacket = new DatagramPacket( data, data.length );
         socket.receive( receivePacket ); // wait for packet
         // display packet contents
         displayMessage( "\nPacket received:" +
            "\nFrom host: " + receivePacket.getAddress() +
            "\nHost port: " + receivePacket.getPort() +
            "\nLength: " + receivePacket.getLength() +
            "\nContaining:\n\t" + new String( receivePacket.getData(),
            0, receivePacket.getLength() ) );
    }
                                                              Transparency No. 1-36
                                                                             Java Networking

    // process problems receiving or displaying packet
       catch( IOException exception ) {
         displayMessage( exception.toString() + "\n" );
         exception.printStackTrace();
       }     } // end while
 } // end method waitForPackets
// utility method called from other threads to manipulate
 // displayArea in the event-dispatch thread
 private void displayMessage( final String messageToDisplay )
 { // display message from event-dispatch thread of execution
    SwingUtilities.invokeLater(
       new Runnable() { // inner class to ensure GUI updates properly
         public void run() // updates displayArea
         { displayArea.append( messageToDisplay );
           displayArea.setCaretPosition( displayArea.getText().length() );
         }

                                                                   Transparency No. 1-37
                                                               Java Networking


       } // end inner class

      ); // end call to SwingUtilities.invokeLater
  }

  public static void main( String args[] )
  {
    Client application = new Client();

  application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    application.waitForPackets();
  }

} // end class Client



                                                       Transparency No. 1-38
                                  Java Networking
The server side program




                          Transparency No. 1-39
                                                                      Java Networking
// Fig. 18.6: Server.java
// Server that receives and sends packets from/to a client.
 import java.io.*; import java.net.*; import java.awt.*;
 import java.awt.event.*; import javax.swing.*;

public class Server extends JFrame {
private JTextArea displayArea;      private DatagramSocket socket;
// set up GUI and DatagramSocket
public Server()
{ super( "Server" );
   displayArea = new JTextArea();
   getContentPane().add( new JScrollPane( displayArea ), BorderLayout.CENTER );
   setSize( 400, 300 );    setVisible( true );
   // create DatagramSocket for sending and receiving packets
   try {
      socket = new DatagramSocket( 5000 );
   }
                                                              Transparency No. 1-40
                                                                         Java Networking
 // process problems creating DatagramSocket
   catch( SocketException socketException ) {
     socketException.printStackTrace();
     System.exit( 1 );
   }
} // end Server constructor
// wait for packets to arrive, display data and echo packet to client
private void waitForPackets()
{
   while ( true ) { // loop forever
     // receive packet, display contents, return copy to client
     try { // set up packet
        byte data[] = new byte[ 100 ];
        DatagramPacket receivePacket = new DatagramPacket( data, data.length );
        socket.receive( receivePacket ); // wait for packet



                                                                 Transparency No. 1-41
                                                                             Java Networking
   // display information from received packet
    displayMessage( "\nPacket received:" +
            "\nFrom host: " + receivePacket.getAddress() +
            "\nHost port: " + receivePacket.getPort() +
            "\nLength: " + receivePacket.getLength() +
            "\nContaining:\n\t" + new String( receivePacket.getData(),
              0, receivePacket.getLength() ) );
        sendPacketToClient( receivePacket ); // send packet to client
         } // process problems manipulating packet
         catch( IOException ioException ) {
           displayMessage( ioException.toString() + "\n" );
           ioException.printStackTrace();
         }       } // end while
    } // end method waitForPackets
    // echo packet to client
private void sendPacketToClient( DatagramPacket receivePacket ) throws IOException
{
                                                                     Transparency No. 1-42
 displayMessage( "\n\nEcho data to client..." );                            Java Networking

 // create packet to send
 DatagramPacket sendPacket = new DatagramPacket(
    receivePacket.getData(), receivePacket.getLength(),
    receivePacket.getAddress(), receivePacket.getPort() );
 socket.send( sendPacket ); // send packet
 displayMessage( "Packet sent\n" );
}
// utility method called from other threads to manipulate
// displayArea in the event-dispatch thread
private void displayMessage( final String messageToDisplay )
{ // display message from event-dispatch thread of execution
   SwingUtilities.invokeLater(
     new Runnable() { // inner class to ensure GUI updates properly
        public void run() // updates displayArea
        { displayArea.append( messageToDisplay );
          displayArea.setCaretPosition( displayArea.getText().length() );
     }
                                                                    Transparency No. 1-43
                                                                   Java Networking



      } // end inner class

     ); // end call to SwingUtilities.invokeLater
 }

 public static void main( String args[] )
 {
   Server application = new Server();

 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   application.waitForPackets();
 }

} // end class Server



                                                           Transparency No. 1-44
                                                                  Java Networking
   Access resources via URLs
 What Is a URL ?
   an acronym for Uniform Resource Locator
   is a reference (an address) to a resource on the Internet.
 Format:
    scheme : [// [host [:port]]] [ path [reference]]
 EXs:
   http://www.cs.nccu.edu.tw
   http://xml.cs.nccu.edu.tw/Courses/java2002/index.html#loc2
   ftp://java.sun.com/pub/
   http://java.sun.com/servlet/app1?user=chen+passwd=****
   file:///D:/chencc/java2002/index.html



                                                          Transparency No. 1-45
                                                                       Java Networking
   Creating a URL
 Direct from URL address
   String j2k = “http://xml.cs.nccu.edu.tw/Courses/java2000”;
   URL j2000 = new URL(j2k); // or
   URL j2000 = new URL
    (“http”, “xml.cs.nccu.edu.tw”, “Courses/java2000”);
 Relative to another URL address
   String coursesLoc = “http://xml.cs.nccu.edu.tw/Courses/index.html”
   URL coursesURL = new URL(coursesLoc);
   URL j2000 = new URL(coursesURL, “java2002/index.html”);
 Constructor Summary
   URL(String spec)
   URL(String scheme, String host [, int port] , String file [,
    URLStreamHandler h])
   URL(URL baseURL, String relativeURL [,URLStreamHandler] )
   possible exception: MalformedURLException               Transparency No. 1-46
                                                               Java Networking
   Parsing a URL
 getProtocol
   Returns the protocol identifier component of the URL.
 getHost
   Returns the host name component of the URL.
 getPort
   Returns the port number component of the URL.
   The getPort method returns an integer that is the port number.
   If the port is not set, getPort returns -1.
 getFile
   Returns the filename component of the URL.
 getRef
   Returns the reference component of the URL.

                                                       Transparency No. 1-47
                                                             Java Networking
   Example
import java.net.*;     import java.io.*;
public class ParseURL {
  public static void main(String[] args) throws Exception {
    URL aURL = new URL("http://java.sun.com:80/docs/books/"
                      + "tutorial/index.html#DOWNLOADING");
    System.out.println("protocol = " + aURL.getProtocol());
    System.out.println("host = " + aURL.getHost());
    System.out.println("filename = " + aURL.getFile());
    System.out.println("port = " + aURL.getPort());
   System.out.println("ref = " + aURL.getRef()); } }
 Here's the output displayed by the program:
    protocol = http              host = java.sun.com
    filename = /docs/books/tutorial/index.html
    port = 80                    ref = DOWNLOADING

                                                     Transparency No. 1-48
                                                         Java Networking
   Reading Directly from a URL
 InputStream openStream(); // return a stream for reading
 EX:
 URL yahoo = new URL("http://www.yahoo.com/");
 BufferedReader in = new BufferedReader( new
   InputStreamReader( yahoo.openStream())       );
String inputLine;
while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
in.close();




                                                 Transparency No. 1-49
                                                      Java Networking
   Connecting to a URL
 URLConnection openConnectino() throws IOException;
 EX:
try {
   URL yahoo = new URL("http://www.yahoo.com/");
   URLConnection yahooConnection = yahoo.openConnection();
   …
   } catch (MalformedURLException e) { // new URL() failed
        ...
   } catch (IOException e) {     // openConnection() failed
        ...
   }
                                              Transparency No. 1-50
                                                         Java Networking
   Reading from and Writing to a URLConnection
 Reading from a URLConnection
// like direct reading from URL using openStream()
    URL yahoo = new URL("http://www.yahoo.com/");
     URLConnection yc = yahoo.openConnection();
     BufferedReader in = new BufferedReader(
                           new InputStreamReader(
                           yc.getInputStream()));
     String inputLine;
     while ((inputLine = in.readLine()) != null)
               System.out.println(inputLine);
     in.close();
                                                 Transparency No. 1-51
                                                               Java Networking
   Writing to a URLConnection
 procedures
  1.Create a URL.
  2.Open a connection to the URL.
  3.Set output capability on the URLConnection.
  4.Get an output stream from the connection. This output stream is
   connected to the standard input stream of the cgi-bin script on the
   server.
  5.Write to the output stream.
  6.Close the output stream.




                                                       Transparency No. 1-52
                                                                   Java Networking


String stringToReverse = URLEncoder.encode(args[0]);
URL url = new URL("http://java.sun.com/cgi-bin/backwards");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(
                 connection.getOutputStream());
out.println("string=" + stringToReverse);
out.close();

BufferedReader in = new BufferedReader( new InputStreamReader(
                        connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) System.out.println(inputLine);
in.close();

                                                           Transparency No. 1-53
                                             Java Networking
  JDBC

 Java DataBase Connectivity
 Allows you to write SQL without worrying about
  what brand of database you‟re connecting to
 Provides a simple interface for database
  programming




                                     Transparency No. 1-54
                                                          Java Networking
   JDBC database URL
 A string used to identify data source ( and parameters)
 The format:
   jdbc: <subprotocol> : <otherStuff>
 “jdbc” means using JDBC
 <subprotocol>: the name of the driver or the name of a database
  connectivity mechanism.
 <otherStuff> : the database identifier. This varies with the
  database driver used.
 the first subprotocol available is the “jdbc-odbc bridge,”
  specified by “odbc”
 EX: String dbUrl =
  "jdbc:odbc://whitehouse.gov:5000/CATS;PWD=Hillary";
                                                  Transparency No. 1-55
                                                          Java Networking



//: c15:Lookup.java
// Looks up email addresses in a local database using JDBC
import java.sql.*;
public class Lookup {
    public static void main(String args[]) {
        String dbUrl = "jdbc:odbc:people";
        String user = ""; String password = "";
        try { // Load the driver (registers itself)
                 Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
                 Connection c = DriverManager.getConnection
                                 ( dbUrl, user, password);
                Statement s = c.createStatement();

                                                  Transparency No. 1-56
                                                       Java Networking



  // SQL code:
ResultSet r = s.executeQuery(
  "SELECT FIRST, LAST, EMAIL FROM people.csv people " +
  "WHERE (LAST='" + args[0] + "') " + " AND (EMAIL Is Not Null)
" + "ORDER BY FIRST");
 while(r.next()) { // Capitalization doesn't matter:
System.out.println( r.getString("Last") + ", " +
r.getString("fIRST") + ": " + r.getString("EMAIL") );
 } } catch(Exception e) { e.printStackTrace(); }
}}



                                               Transparency No. 1-57
                                                     Java Networking
   Servlets
 Servlets are to servers what applets are to browsers
 Servlet API (a standard Java extension) is truly cross-
  platform
 Substitute for CGI scripts
  Easier to write, faster to run
  Not tied to any platform-specific API
 Better than CGI scripts
  Stay resident: speed, persistent
 information
  Multithreading locks prevent collisions
  Session tracking built in

                                             Transparency No. 1-58
                                                         Java Networking
   Running servlets locally

 Download the Tomcat implementation of Java Servlets
  and JSPs
  http://jakarta.apache.org
  Official Servlet/JSP distribution
  Free! Part of Apache project
  Will eventually be integrated into Apache to make it a true
   application server
 Execute Tomcat.bat start




                                                 Transparency No. 1-59
                                                                Java Networking
    Works with both GET & POST
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ServletsRule extends HttpServlet {
 int i = 0;
 // Servlet "persistence"
 public void service(HttpServletRequest req, HttpServletResponse res)
    throws IOException {
  PrintWriter out = res.getWriter();
  out.print("<HEAD><TITLE>");
  out.print("A server-side strategy");
  out.print("</TITLE></HEAD><BODY>");
  out.print("<h1>Servlets Rule! " + i++);
  out.print("</h1></BODY>");
  out.close(); } }
                                                        Transparency No. 1-60
                                                                  Java Networking
    Easy to get HTML form data
// Dumps the name-value pairs of any HTML form
import javax.servlet.*; import javax.servlet.http.*;
import java.io.*;           import java.util.*;
public class EchoForm extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws
     IOException {
   res.setContentType("text/html");
   PrintWriter out = res.getWriter();
   out.print("<h1>Your form contained:</h1>");
   Enumeration flds = req.getParameterNames();
   while(flds.hasMoreElements()) { String field = (String)flds.nextElement();
      String value = req.getParameter(field);
      out.print(field + " = " + value + "<br>");
   }
   out.close(); }
                                                          Transparency No. 1-61
                                                       Java Networking



public void doPost(HttpServletRequest req, HttpServletResponse
   res) throws IOException {
 doGet(req, res);
}}




                                               Transparency No. 1-62
                                                                 Java Networking
    One servlet, thread-per-request
import javax.servlet.*; import javax.servlet.http.*;
import java.io.*;
public class ThreadServlet extends HttpServlet {
 int i;
 public void service(HttpServletRequest req, HttpServletResponse res)
     throws IOException {
  res.setContentType("text/html");
  PrintWriter out = res.getWriter();
  synchronized( this) {
      try { Thread.currentThread().sleep(5000); }
      catch( InterruptedException e) {}
   }
  out.print("<h1>Finished " + i++ + "</h1>");
  out.close(); } }

                                                         Transparency No. 1-63
                                                     Java Networking
   Java Server Pages (JSPs)

 Servlets still require web pages
 Why not combine only the essential servlet code with
  the HTML code?
 Why not minimize the Java code you have to write?
 Inspired by ASPs but much nicer
 The easiest way to experiment with servlet properties
 You can include special servlets, calls to Java libraries,
  etc.



                                             Transparency No. 1-64
                                                      Java Networking
   Java Server Web Dev Kit

 From java.sun.com, exceptionally easy to install and
  run
 All you do is put .jsp files in the appropriate directory,
  point your web browser at them
 JSP is automatically built, compiled and loaded on the
  first call, just like a servlet




                                              Transparency No. 1-65
                                                   Java Networking
   Most code is built for you

<html><body> <H1>The time in seconds is:
 <%= System.currentTimeMillis()/1000 %>
</H1> </body></html>
 Plenty of Java code is produced, +HTML
 The „<%=‟ coerces the resulting expression to a String
 Code automatically rebuilt & recompiled when JSP
  source file changes




                                           Transparency No. 1-66
                                                                   Java Networking
    Basic JSP operations
<%-- This JSP comment will not appear in the generated html --%>
<%-- This is a JSP directive: --%>
<%@ page import="java.util.*" %>
<%-- These are declarations: --%>
<%!
 long loadTime= System.currentTimeMillis();
 Date loadDate = new Date();
 int hitCount = 0;
%>
<html><body>
<%-- The next several lines are the result of a JSP expression inserted in the
   generated html; the '=' indicates a JSP expression --%>
<H1>This page was loaded at <%= loadDate %> </H1>

                                                           Transparency No. 1-67
                                                            Java Networking



<H1>Hello, world! It's <%= new Date() %></H1>
<H2>Here's an object: <%= new Object() %></H2>
<H2>This page has been up <%= (System.currentTimeMillis()-
   loadTime)/1000 %> seconds</H2>
<H3>Page has been accessed <%= ++hitCount %> times since
   <%= loadDate %></H3>
<%-- A "scriptlet" which writes to the server console. Note that a ';'
   is required: --%>
<% System.out.println("Goodbye"); out.println("Cheerio"); %>
</body></html>



                                                    Transparency No. 1-68
                                                             Java Networking
   Extracting fields and values
 You can mix Java code & HTML
 An “if” statement can print HTML in its body

<%-- Fetching the data from an HTML form --%>
<%-- Also generates the form --%>
<%@ page import="java.util.*" %>
<html><body> <H1>DisplayFormData</H1><H3>
<% Enumeration f = request.getParameterNames();
    if(!f.hasMoreElements()) { // No fields       %>
<form method="POST" action="DisplayFormData.jsp">
<% for(int i = 0; i < 10; i++) { %>
Field<%=i%>: <input type="text" size="20" name="Field<%=i%>"
   value="Value<%=i%>"><br> <% } %>

                                                     Transparency No. 1-69
                                                   Java Networking



<INPUT TYPE=submit name=submit Value="Submit"> </form>
<% } %>
<%
  Enumeration flds = request.getParameterNames();
  while(flds.hasMoreElements()) {
    String field = (String)flds.nextElement();
   String value = request.getParameter(field);
%>
<li> <%= field %> = <%= value %> </li>
<% } %>
</H3></body></html>
                                           Transparency No. 1-70
                                                     Java Networking
   Remote Method Invocation (RMI)

 Basic idea: the network of computers becomes the
  computing platform
  Objects can live on other computers
  You can invoke methods on those objects, passing them
   object arguments, and they can return objects
 Network connections and JDBC are particular ways to
  compute across the network, RMI is the general
  solution




                                             Transparency No. 1-71
                                                             Java Networking
   1) Make a Remote Interface
//: Thinking in Java, ch15:rmi: PerfectTimeIF.java
// The PerfectTime remote interface.
package c15.rmi;
import java.rmi.*;
interface PerfectTimeIF extends Remote {
 long getPerfectTime() throws RemoteException;
}




                                                     Transparency No. 1-72
                                                    Java Networking
   2) Create the Remote class

 Create and install
     RMISecurityManager
 Create one or more instances of a remote object
 Register at least one of the remote objects with the RMI
  remote object registry, for bootstrapping purposes




                                            Transparency No. 1-73
                                                               Java Networking


//: c15:rmi:PerfectTime.java
// The implementation of the PerfectTimeIF remote object.
package c15.rmi;
import java.rmi.*;                     import java.rmi.server.*;
import java.rmi.registry.*;            import java.net.*;
public class PerfectTime extends UnicastRemoteObject implements
     PerfectTimeIF {
 // Implementation of the interface:
 public long getPerfectTime() throws RemoteException {
  return System.currentTimeMillis(); }
 // Must implement constructor to throw RemoteException:
 public PerfectTime() throws RemoteException {
  // super() Called automatically
}

                                                       Transparency No. 1-74
                                                      Java Networking



// Registration for RMI serving:
public static void main(String[] args) {
 System.setSecurityManager( new RMISecurityManager());
 try {
   PerfectTime pt = new PerfectTime();
   Naming.bind( "//peppy:2005/PerfectTime", pt);
   System.out.println("Ready to do time");
  }catch(Exception e) { e.printStackTrace(); }
}}




                                              Transparency No. 1-75
                                            Java Networking
   Starting The Registry

 At default port 1099:
  start rmiregistry (Win95)
  rmiregistry & (Unix)
 At specified port:
  start rmiregistry 2005 (Win95)
  rmiregistry 2005 & (Unix)




                                    Transparency No. 1-76
                                               Java Networking
  Creating Stubs & Skeletons

 Must specify location starting from the class path:
  rmic c15.rmi.PerfectTime
 This produces:
  PerfectTime_Stub.class
  PerfectTime_Skel.class
 Now your RMI program can work




                                       Transparency No. 1-77
                                                             Java Networking
   3) Use the Remote Object
//: c15:rmi:DisplayPerfectTime.java
package c15.rmi;
import java.rmi.*;              import java.rmi.registry.*;
public class DisplayPerfectTime {
public static void main(String[] args){
 System.setSecurityManager( new RMISecurityManager());
 try {
    PerfectTimeIF t = (PerfectTimeIF) Naming.lookup
                                 ( "//peppy:2005/PerfectTime");
    for(int i = 0; i < 10; i++)
         System.out.println("Perfect time = " + t.getPerfectTime());
 } catch(Exception e) { e.printStackTrace(); }         }}
                                                     Transparency No. 1-78
                                                                  Java Networking
   Problem 4
 Use Socket to implement a simple file transfer client/server
1. server-side : SftpServer
   1. has a userdata.cfg file, each line of which records a user information
      including: user-name, pass-word and user‟s home directory
   2. Each user can get/put files on his home directory (and subdirectory)
   3. there is a global uploading directory ( say incoming ) to which every
      user can put files
   4. there is a global directory ( say pub) from which every user can get
      files.
   5. to handle simultaneous request of multi users, your server must be
      multithreaded.
2. Client-side : SftpClient


                                                          Transparency No. 1-79
                                                            Java Networking



 pubic class SftpClient {
 // constructor
 public SftpClient(String ip, String port, String user, String passw)
 get(String remoteFilePathName, String localFileName) throws
  IOException, remoteFileNotFound;
 put(String remoteFilePathName, String localFileName) throws
  IOException, RemoteFileNotWritable;
 pubic static void main(String[] args ) { }




                                                    Transparency No. 1-80
                                                               Java Networking
   usage of SftpClient
 java SftpClient Option* {get | put } remotefileName [localName]
 Where Option is any of
   -server ip:port          -user username:passwd
   -terminate
Exs:
   > java SftpClient –server 140.119.162.230:2021 –user chencc:123456
                  get pub/java2000.html D:/temp/java2000.html
   > java SftpClient –server xml.cs.nccu.edu.tw:2021 –user test:1111
                  put incoming/test1.txt test1.txt
 Run the batch to test your client:



                                                       Transparency No. 1-81
                                                          Java Networking
   Problem4Test.bat
Rem launch the server at port 2021
java SftpServer –port 2021
Rem get the file pub/test1.txt from the server
java SftpClient -server localhost:2021 –user test:1111 get
   pub/test1.txt c:\temp\test1.txt
Rem put the file c:\temp\test2.txt to server
java SftpClient –server 127.0.0.1:2021 –user test:1111 put
   incoming/test2.txt c:\temp\test2.txt
Rem terminate the server
java SftpClient –server 127.0.0.1:2021 –user root:1111 -terminate


                                                  Transparency No. 1-82

								
To top