tutorial 5 - ie course information

46
IEG 4180 Tutorial 5 Prepared by Zero (Reuse some content from Chau Wai Shing)

Upload: sampetruda

Post on 05-Dec-2014

921 views

Category:

Documents


4 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Tutorial 5 - IE Course Information

IEG 4180 Tutorial 5

Prepared by Zero(Reuse some content from Chau Wai Shing)

Page 2: Tutorial 5 - IE Course Information

Outline

• Project 3 Overview

• HTTP message exchange

• AJAX

• Java Basic

• Java Network Programming

• Eclipse

Page 3: Tutorial 5 - IE Course Information

Project 3 Overview

Project 3 Overview

• Project 3 is divided into three parts.– Web Console NetProbe Server– SuperNetProbe– JavaNetProbe

Page 4: Tutorial 5 - IE Course Information

Project 3 Overview

Web Console NetProbe Server• Extend the NetProbe Server in Project 2

– Web-UI: open a new TCP port to accept HTTP request from a web browser (Not necessary to use select-base I/O for this port)

• Use web browser to connect to the NetProbe Server, returning a webpage(a form) for user to configure– Maximum number of connections– Start/Stop the Server in receiving Clients’ connections– Killing a particular client connection

• Another page (with AJAX) to show– Number of concurrent transmissions– Statistics of each connection

Page 5: Tutorial 5 - IE Course Information

Project 3 Overview

SuperNetProbe & JavaNetProbe

• SuperNetProbe– Threading (Project 2)– Message-Driven I/O (Project 2)– Alertable overlapped I/O

• JavaNetProbe (with GUI)– Threading– New I/O

Page 6: Tutorial 5 - IE Course Information

HTTP message exchange

HTTP Request

• Browser normally analyze the URL in:

• If no port given, browser normally determines the port number by protocol

• And send (suppose HTTP is used) the following to {host} at {port}

GET /{…path…} HTTP/{…version supported…}

{protocol}://{host}{:port}/{…path…}

Page 7: Tutorial 5 - IE Course Information

HTTP message exchange

HTTP Response• The server then responds:

• Status

HTTP/1.0 200 OK Date: Fri, 31 Dec 1999 23:59:59 GMTContent-Type: text/html Content-Length: 1354

<html> <body> …</body> </html>

200 OK:The request succeeded, and the resulting resource (e.g. file or script output) is returned in the message body.

Page 8: Tutorial 5 - IE Course Information

AJAX

Introduction• AJAX = Asynchronous JavaScript and XML• Mainly based on

– HTML (DOM)– JavaScript– XML

• Goods– Smoother experience

• No need to refresh the whole page• Asynchronize request

– Rich Internet Application• Reference:

– http://www.w3schools.com

Page 9: Tutorial 5 - IE Course Information

AJAX

Idea

• On specific event (e.g.: onload, onClick,…)– Create XMLHttpRequest object– Use XMLHttpRequest to submit further

requests– Handle the response when necessary

Page 10: Tutorial 5 - IE Course Information

AJAX

Example<html><script type="text/javascript">function ajax () { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp= new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp= new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert(“XMLHttpRequest object not supported!"); return false; } } }

xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4){ document.myForm.time.value= xmlHttp.responseText; } } xmlHttp.open("GET","time.asp",true); xmlHttp.send(null);}</script>

<body><form name="myForm“>Name: <input type="text" onkeyup="ajax ();“ name="username" />Time: <input type="text" name="time" /></form></body></html>

src: http://www.w3schools.com/ajax/ajax_server.asp

Page 11: Tutorial 5 - IE Course Information

AJAX

Project Code<html> <head> <title>Web based console</title> <script type='text/javascript'>var xmlhttp;window.onload=GetStatistic;function GetStatistic(){ var UpdateDiv = document.getElementById('Ajax'); //…object creation in previous page xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ UpdateDiv.innerHTML = xmlhttp.responseText; setTimeout('GetStatistic()', 2000); }else{ setTimeout('GetStatistic()', 2000); } } }; xmlhttp.open('post','ajax',true); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); //required by POST xmlhttp.send(null);

} </script> </head><body> <h1>NetProbe Server (Display Panel)</h1> <div id="Ajax"> <p>Current Number of Connections: 0</p> <p>Clients' Statistics</p> <form action="display" method="post"> <table width="800" border="1"> <tr> <td>Client IP Address</td> <td>Protocol</td> <td>Transmission Rate(Bps)</td> <td>Packet Size(Bytes)</td> <td>Bytes Transmitted(Bytes)</td> <td> Time Elapsed(s)</td> </tr> </table><input name="Refresh" type="submit" value="Refresh"> </form> </div> <a href="control">Control Panel</a> </body></html>

Add statistics

Page 12: Tutorial 5 - IE Course Information

Java Basic

Java Basic• Write the program

– Filename extension: .java– Filename should be the same as the public class name– One public class one source file

• Compile and run the program– “javac HelloWorldApp.java”

(you will have “HellpWorldApp.class”)– “java HelloWorldApp” (no extension)

Page 13: Tutorial 5 - IE Course Information

Java Basic

Hello World

Define class name(So filename is HelloWorldApp.java)

public class HelloWorldApp {public static void main (String args[]){

System.out.println(“Hello World!”);}

}

Application entry point; similar to C

Page 14: Tutorial 5 - IE Course Information

Java Basic

Data Type• Primitive Type

– int, boolean, short, char, etc.

• Reference Type– All class object– E.g. String, Integer, Socket, etc.

int a; //a represent the integer itself

a = 123; //just declare and use it

Integer a; //a is only a reference pointer

a = new Integer(123); //you must call new to create the object

Page 15: Tutorial 5 - IE Course Information

Java Basic

Illustration

• Primitive Type

• Reference Type

int a;

a = 123;

a = 456;

nulla 1000

123 1000

456 1010

1010

?a 123456

Integer a;

a = new Integer(123);

a = new Integer(456);

Page 16: Tutorial 5 - IE Course Information

Java Basic

String• String variable1 = “Hello”;• String variable2 = new String(“Hello”);• variable1 += “ World”;• Convert String to int

– int a = Integer.parseInt(“10”);

• Convert int to String– String b = String.valueOf(10);– String b = “” + 10;

Page 17: Tutorial 5 - IE Course Information

Java Basic

Array• Array of primitive new once

int[] arrayInt = new int[10]; // int arrayInt[]

arrayInt[0] = 123;

• Array of reference new twiceClassApple[] apples = new ClassApple[10];

for (int i=0; i<apples.lenght; i++) {

apples[i] = new ClassApple();

}

Page 18: Tutorial 5 - IE Course Information

Java Basic

Creating Array//Primitive type:

//int arrayOfInt[100]; <-- this is wrong

int arrayOfInt[] = new int[10]; //should be in this way

int 2DArrayOfInt[][] = {{1,2},{3,4}}; //Initialize by input array

//Reference type:

Integer arrayOfInteger[] = new Integer[10];

//You have declared 10 reference pointer only

//Remember to new an object for each reference pointer

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

arrayOfInteger[i] = new Integer(0);

}

Integer 2DArrayOfInteger[][] = {{new Integer(1), new Integer(2)},

{new Integer(3), new Integer(4)}}

Page 19: Tutorial 5 - IE Course Information

Java Basic

ArrayList

• ~ non-fixed sized array

• add( ), get( ), size( ), clear( ), remove( ), contains( ) and etc

• Explicit casting on retrieved object from ArrayList

ClassApple apple = new ClassApple();ArrayList list = new ArrayList();list.add(apple);ClassApple apple = (ClassApple)arrayList.get(0);

Page 20: Tutorial 5 - IE Course Information

Java Basic

Access Control

Public: Everywhere can access itPrivate: Permitted only when it occurs within the class

where it is declaredProtected: Permitted only when it occurs within the

subclass object where it is declared or in the same package

public class HelloWorld {public static void main(String args[]) { /* ... * / }private void aPrivateMethod() { /* ... */ }protected void aProtectedMethod() { /* ... */ }

}

Page 21: Tutorial 5 - IE Course Information

Java Basic

Access Control

Class Subclass World

Public

Private

Protected

Page 22: Tutorial 5 - IE Course Information

Java Basic

Memory Management• Java programmer never free allocated

object manually.• JVM will reclaim unreferenced memory

through garbage collection.• Garbage collection is performed

automatically when system is idle or runs out-of memory

• Force garbage collection to start by calling:

System.gc(); //Force the system to start garbage collection

Page 23: Tutorial 5 - IE Course Information

Java Basic

Inheritance

• public ClassA extends ClassB implements ClassC, ClassD { … }

• extends only one Class but implements multiple Interface

• Interface is like a contract, its subclasses must do all it said (give implementation to all declarations in the interface)

Page 24: Tutorial 5 - IE Course Information

Java Basic

Inheritance

• Interface is a fully abstract class, while general abstract class can implement some methods

• If methods of ClassB is not override in ClassA, ClassB’s implementation will be used; all methods are implicitly virtual

• ClassA MUST gives implementation to all methods of ClassC and ClassD

Page 25: Tutorial 5 - IE Course Information

Java Basic

Handling Exception

• To handle exception you either:– Catch it:

– Throw it:

try { Socket s = new Socket(host, port); // … Thread.currentThread().sleep(10);} catch (IOException e) { e.printStackTrace();} catch (Exception e) { System.out.println(e.toString());}

public void connect() throws IOException { Socket s = new Socket(host, port);}

Page 26: Tutorial 5 - IE Course Information

Java Basic

The finally clause

• Some codes may not be executed due to exception:

• Using the finally clause:

try { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) out.println(v.elementAt(i)); out.close( ): // may not be executed} catch (IOException e) { System.err.println(“Caught IOException”);}

try { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) out.println(v.elementAt(i));} catch (IOException e) { System.err.println(“Caught IOException”);} finally { if (out != null) out.close(); }

Page 27: Tutorial 5 - IE Course Information

Java Basic

Creating Thread

• Method 1: Extend the Thread class:

class Primethread extends Thread {

long minPrime;

PrimeThread(long minPrime) { this.minPrime = minPrime; }

public void run() {

// compute primes larger than minPrime

}

}

PrimeThread p = new PrimeThread(143); // create the thread

p.start(); // start the thread

Page 28: Tutorial 5 - IE Course Information

Java Basic

Creating Thread

• Method 2: Implement Runnable and run by a thread:

class PrimeRun implements Runnable {

long minPrime;

PrimeRun(long minPrime) { this.minPrime = minPrime; }

public void run() {

// compute primes larger than minPrime

}

}

Thread aThread = new Thread(new PrimeRun(143));

aThread.start();

Page 29: Tutorial 5 - IE Course Information

Multithread Programming

Mutual Exclusion• Java has the keyword synchronized for mutual

Exclusion• It is applicable to a class, method and a block of

code• Any Java Objects can be used for synchronization

while the Built-in type(int, fload…) cannot

Page 30: Tutorial 5 - IE Course Information

Multithread Programming

Mutual Exclusion• Synchronization on a Block / Statement Level (Use object

for synchronization)Class newThread{

Static Object Lock = new Object(); public someMethod(){

… synchronized(Lock){

// the code that need mutual exclusion }

}

• As Lock is static, so only one instance exists no matter how many newThread instance exists already. As a result, only one thread can run the “Lock” code concurrently

Page 31: Tutorial 5 - IE Course Information

Multithread Programming

Mutual ExclusionSynchronization on a Method / Instance Level: class newThread implements Runnable{

synchronized void someMethod(){ … } }

• It ensure that only one thread can call an object’s method at a time

• But if there are two instances of newThread, then someMethod() can be executed by two different threads concurrently.

Page 32: Tutorial 5 - IE Course Information

Multithread Programming

Mutual ExclusionSynchronization on a Class Level:

class newThread implements Runnable{

static synchronized void someMethod(){

}

}

• This one can be applied for any (Threaded) class methods

Page 33: Tutorial 5 - IE Course Information

Java NIO

Java NIO

• Java New IO package: java.nio

• New features:– Buffer for data of primitive type.– Character-set encoders and decoders.– Channels, a new primitive I/O abstraction.– A multiplexed, non-blocking I/O facility for

writing scalable servers.

Page 34: Tutorial 5 - IE Course Information

Java NIO

Read/Write Through Channel

• Read/Write is done through buffer objects instead of input and output streams.

• Send/Receive chars:Charset charset = Charset.forName("US-ASCII");

CharsetEncoder encoder = charset.newEncoder();

CharsetDecoder decoder = charset.newDecoder();

// write string

sChannel.write(encoder.encode(CharBuffer.wrap("Your msg.")));

// read string

ByteBuffer dbuf = ByteBuffer.allocateDirect(1024);

sChannel.read(dbuf);

dbuf.flip();

String msg = decoder.decode(dbuf).toString();

Page 35: Tutorial 5 - IE Course Information

Java NIO

Read/Write Through Channel

• Read/Write is done through buffer objects instead of input and output streams.

• Send/Receive raw-bytes:// writing raw-bytes

// wrap you data in byte array buf into ByteBuffer object

ByteBuffer buffer = ByteBuffer.wrap(buf);

sChannel.write(buffer);

// read string

ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

sChannel.read(buffer);

Page 36: Tutorial 5 - IE Course Information

Java NIO

ServerSocketChannel• The ServerSocketChannel class is channel-

based socket listener.• It performs the same basic task as the familiar ServerSocket class.

• To create a ServerSocketChannel that listen on a particular port.– – – ServerSocketChannel ssc = ServerSocketChannel.open();

ServerSocket serverSocket = ssc.socket();

serverSocket.bind(new InetSocketAddress(1234));

Page 37: Tutorial 5 - IE Course Information

Java NIO

SocketChannel• SocketChannel acts as the client,

initiating a connection to listening server.• It is the channel-based counterpart of the Socket class.

• To create a SocketChannel that connects to remote server: SocketChannel socketChannel = SocketChannel.open();

socketChannel.connect(new InetSocketAddress("someHost", somePort));

Page 38: Tutorial 5 - IE Course Information

Java NIO

Non-Blocking I/O

• We can configure the I/O operation of a channel to be blocking and non-blocking.

• To configure a channel to be non-blocking:

serverSocketChannel.configureBlocking(false);

socketChannel.configureBlocking(false);

Page 39: Tutorial 5 - IE Course Information

Eclipse

Introduction

• Another IDE– Originally for Java– C++, PHP, COBOL, etc. are also supported

• Similar to NetBean– Written in Java– Require JVM

• Vast amount of plugins available

Page 40: Tutorial 5 - IE Course Information

Eclipse

Where to get it?• Project homepage

http://www.eclipse.org/

• GUI building requires Visual Editor (VE)http://www.eclipse.org/vep/WebContent/main.phpDownload: http://download.eclipse.org/tools/ve/downloads/index.php

• Latest VE support up to Eclipse 3.2http://archive.eclipse.org/eclipse/downloads/drops/R-3.2.2-200702121330/

• For simplicity, download Eclipse, VE, EMF and GEF fromhttp://download.eclipse.org/tools/ve/downloads/drops/R-1.2.3_jem-200701301117/index.html

Page 41: Tutorial 5 - IE Course Information

Eclipse

Startup

Page 42: Tutorial 5 - IE Course Information

Eclipse

Step 11. “New”

2. “Project”

3. ”Java Project"

Page 43: Tutorial 5 - IE Course Information

Eclipse

Console Program - Step 21. “New”

2. “Class”Check the “public static void…” for startup class

Page 44: Tutorial 5 - IE Course Information

Eclipse

Console Program - Step 31. “Run…” /

“Debug…”

2. “Java Application”Select (or use the detected) class as “Main class”

Page 45: Tutorial 5 - IE Course Information

Eclipse

GUI Program - Step 21. “New”

2. “Visual Class”Check the “public static void…” for startup classThis example use “JFrame”

Page 46: Tutorial 5 - IE Course Information

Eclipse

GUI Program - Step 31. “Run…” /

“Debug…”

2. “Java Bean”Select (or use the detected) class as “Java Bean”