IEG 4180 Tutorial 7 - PowerPoint PPT Presentation

1 / 47
About This Presentation
Title:

IEG 4180 Tutorial 7

Description:

Character-set encoders and decoders. Channels, a new primitive I/O abstraction. ... CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder ... – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 48
Provided by: courseIe
Category:
Tags: ieg | encoders | javac | tutorial

less

Transcript and Presenter's Notes

Title: IEG 4180 Tutorial 7


1
IEG 4180 Tutorial 7
  • Prepared by Shing
  • (Remark Modified by Zero)

2
Outline
  • Traditional Blocking I/O
  • Overlapped I/O
  • Event Object Signaling
  • Alertable I/O
  • Java Basic
  • Java Network Programming
  • Eclipse

3
Traditional Blocking I/O
Time Required A B C D
Max Rate Packet Size / Time Required
4
Overlapped I/O
  • When using overlapped I/O, the I/O operation will
    run in the background
  • While the I/O operation runs in the background,
    the application can do some other processing
  • When the I/O operation completes, the application
    is notified
  • There are multiple mechanisms for notifying the
    application that an I/O operation has been
    completed
  • Event Object Signaling
  • Alertable I/O

5
Overlapped I/O
  • Advantages
  • Non-blocking
  • Use application buffers to receive data directly
  • Allow posting multiple receive calls

6
Overlapped I/O Create Overlapped Socket
  • Use WSASocket() instead of socket()
  • Use normal bind(), accept(), connect() etc

7
Overlapped I/O Send Receive Data
  • For TCP, use
  • WSASend()
  • WSARecv()
  • For UDP, use
  • WSASendTo()
  • WSARecvFrom()

8
Overlapped I/O Receive
  • Important parameters for WSARecv and WSARecvFrom
  • Socket
  • Array of WSABUF structures
  • Number of elements in WSABUF array
  • WSAOVERLAPPED structure
  • Pointer to I/O completion routine (used for
    alertable I/O)

9
Overlapped I/O Receive
  • The return value
  • Does not return the number of bytes received.
  • Only tell you it success or error.
  • SOCKET_ERROR may be returned even there was no
    error.
  • Use WSAGetLastError() to check, if error code is
    WSA_IO_PENDING, it means there is no error!!!

10
Overlapped I/O WSABUF
  • The definition of buffer for overlapped I/O
  • len
  • The length of buffer
  • Have to be filled in advance
  • buf
  • The memory space that actually hold the data

typedef struct __WSABUF u_long len char
FAR buf WSABUF, LPWSABUF
11
Overlapped I/O WSAOVERLAPPED structure
  • A mean for notification

typedef struct _WSAOVERLAPPED DWORD Internal
DWORD InternalHigh DWORD Offset DWORD
OffsetHigh WSAEVENT hEvent WSAOVERLAPPED,
LPWSAOVERLAPPED
  • hEvent
  • Function call returns immediately, some
    mechanisms are needed to determine the status and
    the completion of the request
  • Used in event object notification

12
Overlapped I/O The Model - Use of Event Object
Need to Figure Out which Buffer is Being Filled
(or Returned)
13
Overlapped I/O Event Object Notification
  • Create an event object
  • Similar to Mutex and Semaphore, event objects
    also have signaled or nonsignaled state
  • Pass this object to hEvent of the WSAOVERLAPPED
    structure
  • To know when the I/O operation complete
  • WSAWaitForMultipleEvents()
  • To retrieve the results of overlapped operations
  • WSAGetOverlappedResult()
  • Reset the event object to nonsignaled state
  • WSAResetEvent()
  • To free resources occupied by the event object
  • WSACloseEvent()

WSAEVENT WSACreateEvent(void)
14
Overlapped I/O Alertable I/O-Introduction
  • Instead of using event object notification, make
    the OS calls one of your functions when I/O
    operations complete
  • Completion routines
  • Functions that will be called when I/O complete
  • Specified in the last parameter of WSASend() /
    WSASendTo() / WSARecv() / WSARecvFrom()

int i WSARecvFrom(..., lpOverlapped,
lpCompletionRoutine)
15
Overlapped I/O Alertable I/O
Move Data Processing to the Completion Routine
16
Overlapped I/O Alertable I/O -Completion Routines
void CALLBACK CompletionRoutine( IN DWORD
dwError, / the error code / IN
DWORD cbTransferred, / in bytes / IN
LPWSAOVERLAPPED lpOverlapped, / the structure of
this I/O / IN DWORD dwFlags )
  • cbTransferred
  • Number of bytes transferred
  • Equals to zero when connection is closed
  • lpOverlapped
  • hEvent can be freely used by your code, just like
    the LPVOID parameter in thread procedure
  • You have to manage the buffer usage yourself!
  • For example, you issued 10 WSARecv() with 10
    buffers
  • The data will be filled in the buffers according
    to the calling order
  • Reissue WSARecv() on processed buffers

17
Overlapped I/O Alertable Wait state
  • The thread using alertable I/O has to enter
    alertable wait state, so that the completion
    routines can be called
  • To enter alertable wait state
  • Just like the ordinary Sleep()
  • Return when timeout or completion

DWORD SleepEx( DWORD dwMilliseconds, BOOL
bAlertable / set to true / )
18
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)

19
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
20
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
21
Illustration
  • Primitive Type
  • Reference Type

int a a 123 a 456
123
456
Integer a a new Integer(123) a new
Integer(456)
1010
22
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

23
Array
  • Array of primitive ? new once
  • int arrayInt new int10 // int arrayInt
  • arrayInt0 123
  • Array of reference ? new twice
  • ClassApple apples new ClassApple10
  • for (int i0 iltapples.lenght i)
  • applesi new ClassApple()

24
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
25
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.to
String())
public void connect() throws IOException
Socket s new Socket(host, port)
26
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 i0 iltSIZE
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 i0 iltSIZE
i) out.println(v.elementAt(i)) catch
(IOException e) System.err.println(Caught
IOException) finally if (out ! null)
out.close()
27
Inheritance
  • public ClassA extends ClassB implements ClassC,
    ClassD
  • extends only one Class but implements multiple
    Interface

28
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
29
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()
30
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

31
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

32
Mutual Exclusion
  • Synchronization on a Method / Instance Level
  • class newThread implements Runnable
  • synchronized void someMethod()
  • It ensure that only one thread can call an
    objects method at a time
  • But if there are two instances of newThread, then
    someMethod() can be executed by two different
    threads concurrently.

33
Mutual Exclusion
  • Synchronization on a Class Level
  • class newThread implements Runnable
  • static synchronized void someMethod()
  • This one can be applied for any (Threaded) class
    methods

34
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.

35
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") Cha
rsetEncoder encoder charset.newEncoder() Charse
tDecoder decoder charset.newDecoder() // write
string sChannel.write(encoder.encode(CharBuffer.wr
ap("Your msg."))) // read string ByteBuffer dbuf
ByteBuffer.allocateDirect(1024) sChannel.read(d
buf) dbuf.flip() String msg
decoder.decode(dbuf).toString()
36
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(buff
er) // read string ByteBuffer buffer
ByteBuffer.allocateDirect(1024) sChannel.read(buf
fer)
37
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))
38
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("som
eHost", somePort))
39
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) sock
etChannel.configureBlocking(false)
40
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

41
Where to get it?
  • Project homepagehttp//www.eclipse.org/
  • GUI building requires Visual Editor
    (VE)http//www.eclipse.org/vep/WebContent/main.ph
    pDownload http//download.eclipse.org/tools/ve/d
    ownloads/index.php
  • Latest VE support up to Eclipse
    3.2http//archive.eclipse.org/eclipse/downloads/d
    rops/R-3.2.2-200702121330/
  • For simplicity, download Eclipse, VE, EMF and GEF
    fromhttp//download.eclipse.org/tools/ve/download
    s/drops/R-1.2.3_jem-200701301117/index.html

42
Startup
43
Step 1
  • New
  • Project
  • Java Project"

44
Console Program - Step 2
  • New
  • ClassCheck the public static void for
    startup class

45
Console Program - Step 3
  • Run / Debug
  • Java ApplicationSelect (or use the detected)
    class as Main class

46
GUI Program - Step 2
  • New
  • Visual ClassCheck the public static void
    for startup classThis example use JFrame

47
GUI Program - Step 3
  • Run / Debug
  • Java BeanSelect (or use the detected) class as
    Java Bean
Write a Comment
User Comments (0)
About PowerShow.com