Java API Essentials: (Part II)
Java API Essentials: (Part II)
(Part II)
Lab Objective
More exercises on
Threads
Exercise on threads
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
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
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
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
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
Java Threads
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
There are two ways to create a Java thread: 1. Extend the java.lang.Thread class
2. Implement the java.lang.Runnable interface
16
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
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
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
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
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
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
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
7 8 2 5 9 3 6 10 34
References
http://java.sun.com/docs/books/tutorial/essential/con currency/
35