You are on page 1of 35

Java API Essentials

(Part II)

Web Languages Course 2009 University of Trento

Lab Objective

More exercises on

Object serialization Client-Server application through sockets

Refresh basic Java concepts on

Threads

Exercise on threads

The TCPPortScanner application


2

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.net and java.io.Serializable to transport Java objects through the network

Sockets

Endpoint of 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.

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 Implements the client side of the connection Used to connect to a specific port in a server machine
5

java.net.Socket

Socket TCP
Constructor
Socket(String host, int port)
Socket(InetAddress address, int port) ServerSocket(int port)

Create
a stream socket and connects it to the specified port number on the named host. a stream socket and connects it to the specified port number at the specified IP address a server socket, bound to the specified port . a server socket and binds it to the specified local port number, with the specified backlog (maximum queue length for incoming connection)
6

ServerSocket(int port, int backlog )

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 throw the exception InterruptedIOException
7

EchoClient
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); }
8

EchoServer
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.");
9

EchoServer
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); }

10

Exercises (15 min.)


1.

Test EchoServer.java and EchoClient.java: use the client EchoClient.java to invoke the service provided by EchoServer.java 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 through sockets)

2.

11

TCP client example


makes 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]); Or with timeout: s = new Socket(); s.connect(new InetSocketAddress(host, port), timeout);

blocking (timeout)

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());}} } }

Error Handling

12

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
13

Java Threads

The package java.lang.*

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

15

How to create Java Threads

There are two ways to create a Java thread: 1. Extend the java.lang.Thread class
2. Implement the java.lang.Runnable interface

16

Extending the Thread class

In order to create a new thread we may subclass java.lang.Thread and 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 the start method.
17

Example I
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"); } } 18

Example I
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 in parallel } }

19

Example I

Typical output of the previous example: starts its execution says: ping starts its execution says: pong says: ping says: pong says: ping says: pong says: ping says: pong says: ping says: pong finished execution finished execution
20

thread1 thread1 thread2 thread2 thread1 thread2 thread1 thread2 thread1 thread2 thread1 thread2 thread1 thread2

Implementing the Runnable interface

In order to create a new thread we may also provide a 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 method of the runnable object
21

Example II
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"); } } 22

Example II
public class A { private String value; public A(String value) { this.value = value; } public String getValue() { return value; } Shared variable } 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(); } }

23

Example II

Typical output of the previous example:

thread1 thread1 thread2 thread2 thread1 thread2 thread1 thread2 thread1 thread2 thread1 thread2 thread1 thread2

starts execution says: some value starts execution says: some value says: some value says: some value says: some value says: some value says: some value says: some value says: some value says: some value finished execution finished execution
24

Supporting Multiple Connection


Or:

makes a connection for each client and then echoes the clients request

Connection c = new Connection(clientSocket); import java.net.*; c.start(); 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()); } } }

25

Supporting Multiple Connection

makes a connection for each client and then echoes the clients request
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 server String data = in.readObject(); out.writeObject(data); }catch(IOException e){ System.out.println("IO:"+e.getMessage()); } 26

Exercises (15 min.)


4.

Modify the server code of the previous exercises (EchoServer.java, DateServer, RevertStringServer) so that it can accept multiple connections (a thread is started once a connection is opened)

27

Synchronization of Threads

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 modifies the state of an object then the method should be declared 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.
28

Synchronization of Threads
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 or wait() is called inside the synchronized method.

29

Synchronization of Threads

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... }
30

Summary Exercise

TCP PortScanner

Summary Exercise: TCPPortScanner


Realize an application which : Scans all ports (from number X to number Y) of a specific host, with only 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 and parallel threads)

Assumptions: Scanning a port means checking if the given port is open or not to a socket connection; Y is greater than X N is minor or equal to Y-X; N, X e Y can be specified as input parameters

32

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 1 2 3 4 5 6 7 8 9 10 State OPEN CLOSED CLOSED CLOSED OPEN CLOSED CLOSED OPEN CLOSED CLOSED 33

TCPPortScanner : Log Info


Thread-0 SCANNING PORT: Thread-0 SCANNING PORT: Thread-0 SCANNING PORT: 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: Thread-3 SCANNING PORT: Thread-1 SCANNING PORT: Thread-2 SCANNING PORT: Thread-3 SCANNING PORT: Thread-1 SCANNING PORT: Thread-2 SCANNING PORT: Thread-3 SCANNING PORT: 2 3 10

7 8 2 5 9 3 6 10 34

References

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

35

You might also like