320 likes | 545 Views
IEG 4180 Tutorial 7. Liu Ke Re-use content from Chau Wai Shing. Outline. Project 3 File Access in C++ File Access in C (Binary) Multithread Programming Java I/O Java NIO. Project 3. Architecture & Example Components Streaming Flow Control Error Handling. Architecture & Example.
E N D
IEG 4180 Tutorial 7 Liu Ke Re-use content from Chau Wai Shing
Outline • Project 3 • File Access in C++ • File Access in C (Binary) • Multithread Programming • Java I/O • Java NIO
Project 3 • Architecture & Example • Components • Streaming • Flow Control • Error Handling
Architecture & Example http://localhost:8080/192.168.1.100/10000/1024/tcp/media.mpg Media Player Port = 10000 Folder = c:\media HTTP Server Streaming Client Streaming Server Port = 8080 Folder = c:\temp Wait few seconds for buffering media.mpg media.mpg Server IP = 192.168.1.100 Server Port = 10000 Packet size = 1024 Protocol = tcp Filename = media.mpg Project 3
Components • Streaming Server • Supporting at least three clients at the same time • Startup parameters (listen port and shared folder) (GUI or console) • Support NetProbe Client in Project 2 • Streaming Client and HTTP Server • Support different media players (RealPlayer, Windows Media Player) • Parameters input (listen port and caching folder) (GUI or console) • Support different media types (.mpg, .rm, .mp3) • Return appropriate HTTP reply to media player if streaming cannot start • Accept special URL from media players to specify streaming behaviour from specified Streaming Server (protocol, packet size, transfer rate) Project 4
Streaming • Startup latency < 10s • Completion of streaming of whole media for TCP • Smoothness • Streaming media file via TCP • Streaming media file via UDP • Flow control in case of UDP • Packet loss recovery is optional • Streaming is stopped when media player is closed Project 4
Flow Control • It's up to you to design the flow control for use in your implementation. • Explain flow control mechanism clearly in documentation • For example • Fixed sending rate • Client controls the sending rate in real time • Make sure the sending rate is sufficient • The playing speed is different for different media files • Fixed sending rate maybe not suitable for some media files. • Media player would be forced to pause or even stop Project 4
Error Handling • Different type of errors • File Not Found • Wrong streaming server IP address or port • Return HTTP reply to media player • 404 File Not Found • 200 OK Project 4
File Access in C++ • CFile Class • nOpenFlags • Example
CFile Class • CFile is a class in MFC for accessing the file • CFile::CFile //Constuctor • CFile(LPCTSTR lpszFileName, UINT nOpenFlags); • lpszFileName • A string that is the path to the desired file. The path can be relative or absolute. • nOpenFlags • Sharing and access mode. File Access in C++
nOpenFlags • CFile::modeCreate • Directs the constructor to create a new file. If the file exists already, it is truncated to 0 length • CFile::modeRead • Opens the file for reading only • CFile::modeWrite • Opens the file for writing only File Access in C++
nOpenFlags (cont.) • nOpenFlags • CFile::shareDenyNone • Opens the file without denying other processes read or write access to the file. • CFile::shareDenyRead • Opens the file and denies other processes read access to the file. • CFile::shareDenyWrite • Opens the file and denies other processes write access to the file. • CFile infile(infilename, • CFile::modeRead | CFile::shareDenyNone); • CFile outfile(outfilename, • CFile::modeWrite | CFile::shareDenyNone); File Access in C++
Read and Write • virtual UINT Read( void* lpBuf, UINT nCount ); • lpBuf – pointer of buffer • nCount – maximum number of bytes to read from file • Return the actual number of bytes read from file • virtual void Write( const void* lpBuf, UINT nCount ); • lpBuf – pointer of buffer • nCount – maximum number of bytes to write to file File Access in C++
Example CString infilename = "k.mp3"; CString outfilename = "a.mp3"; CFile infile(infilename, CFile::modeRead | CFile::shareDenyNone); CFile outfile(outfilename, CFile::modeWrite | CFile::shareDenyNone); int num; char *inbuf = new char[1024]; while ((num = infile.Read(inbuf, 1024)) > 0) { outfile.Write(inbuf, num); } infile.Close(); outfile.Close(); File Access in C++
File Access in C (Binary) • Basic Syntax • Binary Access
Basic Syntax FILE *fp;int tmp;fp = fopen(“test.txt”, “r”);while (fscanf(fp, “%d\n”, &tmp) != EOF){ //..do something}fclose(fp); File name Mode of Access Basic Flags: r :Read w :Write a :Append Additional Flags b :Binary + :Different for Basic Flag File Access in C (Binary)
Binary Access FILE *fp;int elementCnt = 1024;char readBuf[elementCnt];fp = fopen(“test.txt”, “rb”);while (fread(readBuf, sizeof(char), elementCnt, fp) == elementCnt){ //..byte-by-byte read, do something, e.g.: send the sendBuf}//..do something if sendBuf not handledfclose(fp); Size of element, in this case it would be 1 Max. number of element to be read If return value not equal to elementCnt provided, most likely EOF reached File Access in C (Binary)
Multithread Programming • Thread Priority • Producer-Consumer Model • Timer
Thread Priority • Methods for get/set thread priority: • getPriority() • setPriority() • Priority range from 1-10 • Three default constant: • MAX_PRIORITY(10) • MIN_PRIORITY(1) • NORM_PRIORITY(default priority:5) • e.g. SomeThread.setPriority(MAX_PRIORITY); Multithread Programming
Producer FIFO Queue Consumer Producer-Consumer Model Problem 1: Mutual exclusion in accessing the queue Solution to problem 1: Use the keyword synchronized in Java Multithread Programming
Producer-Consumer Model Problem 2: Producer needs to be suspended if the queue is full and it needs to be waked up when the queue has vacant space Problem 3: Consumer needs to be suspended if the queue is empty and it needs to be waked up when the queue become non-empty Multithread Programming
Producer-Consumer Model Solution to problem 2 and 3: • The java object class implements several methods for inter-thread synchronization: wait(), notify() • wait() • Causes current thread to wait until another thread invokes the notify() method for this object • notify() • Wake up a single thread that is waiting on this object’s monitor • If multiple threads are waiting on this object, one of them is chosen to be awakened Multithread Programming
Producer-Consumer Example Multithread Programming
Timer • An application may needs to run a task once at some future time or at regular intervals • Possible to use Thread to accomplish these jobs • To make life easier, Java introduce Timer class after version 1.3 • Create background thread to handle task Multithread Programming
Timer … Timer t1 = new Timer(); t1.schedule(new OneShotTask(), 1000) //do this task after one second Timer t2 = new Timer(); t2.schedule(new repeatTask(), 1000, 500) // start carry out the task after 1 second and repeat it every 0.5 second class OneShotTask extends TimerTask{ public void run(){…} } class repeatTask extends TimerTask{ public void run(){…} } Multithread Programming
Java IO • Base on concept of stream • Stream of bytes • InputStream / OutputStream • Byte array as content • Reader / Writer • String as content • Buffered* • Improving I/O performance
Example BufferedReader br = new BufferedReader(new FileReader(“a”)); BufferedWriter bw = new BufferedWriter(new FileWriter(“b”)); String tmp = null; while ((tmp = br.readLine()) != null) bw.write(tmp); bw.close(); br.close(); Java I/O
Important I/O classes Remark: Buffered* can also wrap streams of socket / channel Java I/O
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. Java NIO
Selected-Based I/O • Step 1: Create a Selector Object: • Step 2: Register Channel with the Selector: • Step 3: Wait for events: Selector selector =SelectorProvider.provider().openSelector();; channel.register(selector, SelectionKey.OP_ACCEPT); while (selector.select() > 0) { // process event … } Java NIO
Selected-Based I/O • Step 4: Handle the event: while (selector.select() > 0) { // Get set of ready objects Set readyKeys = selector.selectedKeys(); Iterator readyItor = readyKeys.iterator(); // Walk through set while (readyItor.hasNext()) { // Get key from set SelectionKey key = (SelectionKey)readyItor.next(); readyItor.remove(); // Remove current entry // Get channel SocketChannel keyChannel = (SocketChannel)key.channel(); // do something with the SocketChannel } } Java NIO
Useful Links for Java New I/O • http://developer.java.sun.com/developer/technicalArticles/releases/nio/ • http://java.sun.com/j2se/1.4/docs/guide/nio/index.html Java NIO