Java Essential 2

download Java Essential 2

of 35

Transcript of Java Essential 2

  • 7/27/2019 Java Essential 2

    1/35

    Java API Essentials(Part II)

    Web Languages Course 2009

    University of Trento

  • 7/27/2019 Java Essential 2

    2/35

    2

    Lab Objective More exercises on

    Object serialization

    Client-Server application through sockets Refresh basic Java concepts on

    Threads

    Exercise on threads The TCPPortScannerapplication

  • 7/27/2019 Java Essential 2

    3/35

    3

    The java.net package

    The package java.net provides support for

    sockets programming

    The package java.net contains: Socket, URL,InetAddress, ServerSocket, etc.

    Sockets + Object Serialization: combine java.netand java.io.Serializable to transport Javaobjects through the network

  • 7/27/2019 Java Essential 2

    4/35

    4

    Sockets

    Endpointof a two-way communication link between two

    programs running on the network.

    An endpoint is a combination of an IP address and a

    port number.

    Every TCP connection can be uniquely identified by its

    two endpoints.

  • 7/27/2019 Java Essential 2

    5/35

    5

    TCP Sockets

    Connection-oriented sockets, almost always based on

    TCP

    java.net.ServerSocket

    Implements the server side of the connection Used to listen for connection requests from clients; Should be bound to a known port to listen on, Its accept method blocks until a client requests a connection

    java.net.Socket Implements the client side of the connection Used to connect to a specific port in a server machine

  • 7/27/2019 Java Essential 2

    6/35

    6

    Socket TCP

    Constructor Create

    Socket(String host, int

    port)

    a stream socket and connects it to thespecifiedport number on the named

    host.

    Socket(InetAddress address,

    int port)

    a stream socket and connects it to thespecifiedport number at the

    specified IP address

    ServerSocket(int port)

    a server socket, bound to the specified

    port .

    ServerSocket(int port, int

    backlog )

    a server socket and binds it to thespecified localport number, with the

    specifiedbacklog (maximum queue

    length for incoming connection)

  • 7/27/2019 Java Essential 2

    7/35

    7

    Socket Timeout

    If data are not available (e.g., the host is not reachable),

    the reading methods remain blocked

    To solve the problem: use the setSoTimeout()

    method

    Socket s = new Socket();

    s.setSoTimeout(1000); //time out in millisecond

    When a timeout is set, all the following operations throwthe exception InterruptedIOException

  • 7/27/2019 Java Essential 2

    8/35

    8

    try {

    //Create connection to the server "localhost" on port 8189

    s = new Socket("localhost",8189);

    //Set streams to read from and write to a socket

    s_in = new BufferedReader(new

    InputStreamReader(s.getInputStream()));

    s_out = new PrintWriter(s.getOutputStream(),true);

    System.out.println(s_in.readLine());

    //Set input stream for reading from console

    console = new BufferedReader(new InputStreamReader(System.in));

    String user_input; String received;

    while(true){user_input = console.readLine();

    s_out.println(user_input);

    received = s_in.readLine();

    System.out.println(received);

    }

    EchoClient

  • 7/27/2019 Java Essential 2

    9/35

    9

    try {

    ServerSocket s = new ServerSocket (8189);

    //Wait for the client

    Socket client = s.accept();

    System.out.println(Connection requested from host: " +incoming.getInetAddress().getHostName() +

    "\nto port: " + incoming.getLocalPort() +

    "\nfrom port: " + incoming.getPort() +

    "\nwith IP: " +

    incoming.getInetAddress().getHostAddress());

    BufferedReader in = new BufferedReader (new InputStreamReader

    (incoming.getInputStream ()));

    PrintWriter out = new PrintWriter (incoming.getOutputStream

    (), true);

    out.println ("Hello! Enter BYE to exit.");

    EchoServer

  • 7/27/2019 Java Essential 2

    10/35

    10

    boolean go = true;

    String line;

    while (go){

    line = in.readLine ();

    out.println ("Echo: " + line);if (line.trim().equals("BYE")){

    go = false;

    }

    }

    incoming.close ()

    } catch (IOException e) {System.out.println ("Error. " + e);

    }

    EchoServer

  • 7/27/2019 Java Essential 2

    11/35

    11

    Exercises (15 min.)

    1. Test EchoServer.java and EchoClient.java:

    use the client EchoClient.java to invoke the service

    provided by EchoServer.java

    2. Write a client-server application so that when the client

    connect to the server, the server replies by sending a

    Date object to the client (Object Serialization throughsockets)

  • 7/27/2019 Java Essential 2

    12/35

    12

    TCP client examplemakes connection to server, sends request and receives reply

    import java.net.*;

    import java.io.*;

    public class TCPClient {

    public static void main (String args[]) {

    // arguments supply message and hostname of destination

    Socket s = null;

    try{

    int serverPort = 7896;

    s = new Socket(args[1], serverPort);ObjectInputStream in = new ObjectInputStream( s.getInputStream());

    ObjectOutputStream out = new ObjectOutputStream( s.getOutputStream());

    out.writeUTF(args[0]);

    String data = in.readUTF();

    System.out.println("Received: + data) ;

    }catch (UnknownHostException e){

    System.out.println("Sock:"+e.getMessage());

    }catch (EOFException e){System.out.println("EOF:"+e.getMessage());

    }catch (IOException e){System.out.println("IO:"+e.getMessage());}

    }finally {if(s!=null) try {s.close();}catch (IOException e)

    {System.out.println("close:"+e.getMessage());}}

    } }

    ErrorHandling

    Or with timeout:

    s = new Socket();s.connect(new InetSocketAddress(host, port),

    timeout);

    blocking

    (timeout)

  • 7/27/2019 Java Essential 2

    13/35

    13

    Exercise (15 min.)

    3. Write a client-server application so that: The client process (StringClient.java) :

    - Creates an ArrayList object and fill it with 3-5 String object- Displays the content of the object

    - Sends the object to the server

    - Receives an object from the server

    - Displays the content of the object received

    The server process (StringServer.java):- Receives an ArrayList object from the client- Reverts the strings contained in the object received

    - Creates a new ArrayList object filled with the reversed strings

    - Sends the object created to the client

  • 7/27/2019 Java Essential 2

    14/35

    Java Threads

    The package java.lang.*

  • 7/27/2019 Java Essential 2

    15/35

    15

    Threads

    A thread is a lightweight process a single sequential

    flow of execution within a program

    Threads make possible the implementation of programs

    that seem to perform multiple tasks at the same time

    (e.g. multi-threaded Web servers)

    A new way to think about programming

  • 7/27/2019 Java Essential 2

    16/35

    16

    How to create Java Threads

    There are two ways to create a Java thread:

    1. Extend the java.lang.Threadclass

    2. Implement the java.lang.Runnable

    interface

  • 7/27/2019 Java Essential 2

    17/35

    17

    Extending the Thread class

    In order to create a new thread we may subclassjava.lang.Threadand customize what the thread

    does by overriding its empty run method.

    The run method is where the action of the thread

    takes place.

    The execution of a thread starts by calling thestart method.

  • 7/27/2019 Java Essential 2

    18/35

    18

    Example I 1

    public class MyThread extends Thread{

    private String name, msg;

    public MyThread(String name, String msg) {

    this.name = name;

    this.msg = msg;

    }

    public void run() {

    System.out.println(name + " starts its execution");

    for (int i = 0; i < 5; i++) {

    System.out.println(name + " says: " + msg);

    try {Thread.sleep(5000);

    } catch (InterruptedException ie) {}

    }

    System.out.println(name + " finished execution");

    }

    }

  • 7/27/2019 Java Essential 2

    19/35

    19

    Example I 2

    public class Test1 {

    public static void main(String[] args) {

    MyThread mt1 = new MyThread("thread1", "ping");

    MyThread mt2 = new MyThread("thread2", "pong");

    mt1.start();

    mt2.start();

    }

    }

    The threads run inparallel

  • 7/27/2019 Java Essential 2

    20/35

    20

    Example I 3

    Typical output of the previous example:

    thread1 starts its execution

    thread1 says: ping

    thread2 starts its execution

    thread2 says: pong

    thread1 says: ping

    thread2 says: pong

    thread1 says: ping

    thread2 says: pong

    thread1 says: pingthread2 says: pong

    thread1 says: ping

    thread2 says: pong

    thread1 finished execution

    thread2 finished execution

  • 7/27/2019 Java Essential 2

    21/35

    21

    Implementing the Runnable

    interface

    In order to create a new thread we may also providea class that implements the java.lang.Runnable

    interface

    Preferred way in case our class has to subclass

    some other class

    The threads logic is included inside the run methodof the runnable object

  • 7/27/2019 Java Essential 2

    22/35

    22

    Example II 1

    public class MyClass implements Runnable {

    private String name;

    private A sharedObj;

    public MyClass(String name, A sharedObj) {

    this.name = name; this.sharedObj = sharedObj;

    }

    public void run() {

    System.out.println(name + " starts execution");

    for (int i = 0; i < 5; i++) {

    System.out.println(name + " says: " + sharedObj.getValue());

    try{

    Thread.sleep(5000);} catch (InterruptedException ie) {}

    }

    System.out.println(name + " finished execution");

    }

    }

  • 7/27/2019 Java Essential 2

    23/35

    23

    Example II 2

    public class A {

    private String value;

    public A(String value) { this.value = value; }

    public String getValue() {

    return value;

    }

    }

    public class Test2 {

    public static void main(String[] args) {

    A sharedObj = new A("some value");

    Thread mt1 = new Thread(new MyClass("thread1", sharedObj));

    Thread mt2 = new Thread(new MyClass("thread2", sharedObj));mt1.start(); mt2.start();

    }

    }

    Shared variable

  • 7/27/2019 Java Essential 2

    24/35

    24

    Example II 3

    Typical output of the previous example:

    thread1 starts execution

    thread1 says: some value

    thread2 starts execution

    thread2 says: some value

    thread1 says: some value

    thread2 says: some value

    thread1 says: some value

    thread2 says: some value

    thread1 says: some value

    thread2 says: some value

    thread1 says: some value

    thread2 says: some value

    thread1 finished execution

    thread2 finished execution

  • 7/27/2019 Java Essential 2

    25/35

    25

    Supporting Multiple Connection 1makes a connection for each client and then echoes the clients

    request

    import java.net.*;

    import java.io.*;

    public class TCPServer {

    public static void main (String args[]) {

    try{

    int serverPort = 7896;

    ServerSocket listenSocket = new ServerSocket(serverPort);

    while(true) {

    Socket clientSocket = listenSocket.accept();

    (new Thread(new Connection(clientSocket))).start();

    }

    }catch(IOException e){S

    System.out.println("Listen :"+e.getMessage());

    }

    }

    }

    Or:

    Connection c = new Connection(clientSocket);

    c.start();

  • 7/27/2019 Java Essential 2

    26/35

    26

    public class Connection implements Runnable{

    ObjectInputStream in;

    ObjectOutputStream out;

    Socket clientSocket;

    public Connection (Socket s) {

    try {

    clientSocket = s;in = new ObjectInputStream( s.getInputStream());

    out = new ObjectOutputStream( s.getOutputStream());

    } catch(IOException e)

    {System.out.println("Connection: + e.getMessage());}

    }

    public void run(){

    try {// an echo serverString data = in.readObject();

    out.writeObject(data);

    }catch(IOException e){

    System.out.println("IO:"+e.getMessage());

    }

    Supporting Multiple Connection 2makes a connection for each client and then echoes the clients

    request

  • 7/27/2019 Java Essential 2

    27/35

    27

    Exercises (15 min.)

    4. Modify the server code of the previous exercises(EchoServer.java, DateServer,

    RevertStringServer) so that it can accept multipleconnections (a thread is started once a connection isopened)

  • 7/27/2019 Java Essential 2

    28/35

    28

    Synchronization of Threads 1

    In many cases concurrently running threads share data

    and must consider the state and activities of other

    threads

    If two threads can both execute a method that modifiesthe state of an object then the method should bedeclared to be synchronized, allowing only one

    thread to execute the method at a time.

    If a class has at least one synchronized methods, each

    instance of it has a monitor. A monitor is an object that

    can block threads and notify them when it is available.

  • 7/27/2019 Java Essential 2

    29/35

    29

    Example:

    public synchronized void updateRecord() {

    // critical code goes here

    }

    Only one thread may be inside the body of this function.

    A second call will be blocked until the first call returns orwait() is called inside the synchronized method.

    Synchronization of Threads 2

  • 7/27/2019 Java Essential 2

    30/35

    30

    The Thread class has a method, join(), which

    allows an object to wait until the thread terminates

    public void myMethod() {

    // Do some work here...

    //Can't proceed until another thread is done:otherThread.join();

    //Continue work...

    }

    Synchronization of Threads 3

  • 7/27/2019 Java Essential 2

    31/35

    Summary Exercise

    TCP PortScanner

  • 7/27/2019 Java Essential 2

    32/35

    32

    Summary Exercise:

    TCPPortScanner

    Realize an application which :

    Scans all ports (from numberX to numberY) of a specific host, withonly one thread of execution

    Scans the same ports in parallel, by using N threads

    Stores log info into a log file (or console)

    Stores the scan results into a file

    Check and prints the execution time in both cases (single thread andparallel threads)

    Assumptions:

    Scanning a portmeans checking if the given port is open or not to a

    socket connection; Y is greater than X

    N is minor or equal toY-X;

    N, X e Y can be specified as input parameters

  • 7/27/2019 Java Essential 2

    33/35

    33

    TCPPortScanner :

    Expected Output----- Port Scanning Report -----

    Date: Sun Feb 24 21:47:20 CET 2008

    Scanned Host: localhost

    From port: 1

    To port: 10

    Execution Time (1 thread): 7 sec

    Execution Time (3 threads): 1 sec

    Port State

    1 OPEN

    2 CLOSED

    3 CLOSED

    4 CLOSED5 OPEN

    6 CLOSED

    7 CLOSED

    8 OPEN

    9 CLOSED

    10 CLOSED

  • 7/27/2019 Java Essential 2

    34/35

    34

    TCPPortScanner :

    Log InfoThread-0 SCANNING PORT: 2

    Thread-0 SCANNING PORT: 3

    Thread-0 SCANNING PORT: 10

    port per Threads: 3

    left Ports: 1

    Thread: 0 from 1 to 3

    Thread: 1 from 4 to 6

    Thread: 2 from 7 to 10

    .

    Thread-3 SCANNING PORT: 7

    Thread-3 SCANNING PORT: 8

    Thread-1 SCANNING PORT: 2

    Thread-2 SCANNING PORT: 5

    Thread-3 SCANNING PORT: 9

    Thread-1 SCANNING PORT: 3

    Thread-2 SCANNING PORT: 6

    Thread-3 SCANNING PORT: 10

  • 7/27/2019 Java Essential 2

    35/35

    35

    http://java.sun.com/docs/books/tutorial/essential/con

    currency/

    References

    http://java.sun.com/docs/books/tutorial/essential/concurrency/http://java.sun.com/docs/books/tutorial/essential/concurrency/http://java.sun.com/docs/books/tutorial/essential/concurrency/http://java.sun.com/docs/books/tutorial/essential/concurrency/http://www.mindview.net/Books/TIJ/