Title: IEG 4180 Tutorial 7
1IEG 4180 Tutorial 7
- Prepared by Shing
- (Remark Modified by Zero)
2Outline
- Traditional Blocking I/O
- Overlapped I/O
- Event Object Signaling
- Alertable I/O
- Java Basic
- Java Network Programming
- Eclipse
3Traditional Blocking I/O
Time Required A B C D
Max Rate Packet Size / Time Required
4Overlapped 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
5Overlapped I/O
- Advantages
- Non-blocking
- Use application buffers to receive data directly
- Allow posting multiple receive calls
6Overlapped I/O Create Overlapped Socket
- Use WSASocket() instead of socket()
- Use normal bind(), accept(), connect() etc
7Overlapped I/O Send Receive Data
- For TCP, use
- WSASend()
- WSARecv()
- For UDP, use
- WSASendTo()
- WSARecvFrom()
8Overlapped 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)
9Overlapped 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!!!
10Overlapped 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
11Overlapped I/O WSAOVERLAPPED structure
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
12Overlapped I/O The Model - Use of Event Object
Need to Figure Out which Buffer is Being Filled
(or Returned)
13Overlapped 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)
14Overlapped 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)
15Overlapped I/O Alertable I/O
Move Data Processing to the Completion Routine
16Overlapped 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
17Overlapped 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 / )
18Java 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)
19Hello 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
20Data 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
21Illustration
- Primitive Type
- Reference Type
int a a 123 a 456
123
456
Integer a a new Integer(123) a new
Integer(456)
1010
22String
- 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
23Array
- 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()
24Memory 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
25Handling 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)
26The 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()
27Inheritance
- public ClassA extends ClassB implements ClassC,
ClassD - extends only one Class but implements multiple
Interface
28Creating 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
29Creating 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()
30Mutual 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
31Mutual 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
32Mutual 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.
33Mutual Exclusion
- Synchronization on a Class Level
- class newThread implements Runnable
- static synchronized void someMethod()
-
-
-
- This one can be applied for any (Threaded) class
methods
34Java 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.
35Read/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()
36Read/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)
37ServerSocketChannel
- 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))
38SocketChannel
- 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))
39Non-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)
40Introduction
- 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
41Where 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
42Startup
43Step 1
- New
- Project
- Java Project"
44Console Program - Step 2
- New
- ClassCheck the public static void for
startup class
45Console Program - Step 3
- Run / Debug
- Java ApplicationSelect (or use the detected)
class as Main class
46GUI Program - Step 2
- New
- Visual ClassCheck the public static void
for startup classThis example use JFrame
47GUI Program - Step 3
- Run / Debug
- Java BeanSelect (or use the detected) class as
Java Bean