Lecture 5 Nonblocking I/O and Multiplexing Erick Pranata © Sekolah Tinggi Teknik Surabaya 1
2
» Socket I/O calls may block for several reasons ˃Data Input (if data not available) +Read() +Receive() +ReceiveFrom() ˃Data Output (if no sufficient space) +Write() +Send() +SendTo() ˃Listener (until connection established) +Accept() +AcceptSocket() +AcceptTcpClient() 3 © Sekolah Tinggi Teknik Surabaya
» Problems in connection establishment ˃Long round-trip times ˃High error rate connections ˃Slow (or deceased) server » Blocking method call halts the execution of application » Solution: ˃I/O Status Prechecking ˃Blocking Calls with Timeout ˃Nonblocking Sockets 4 © Sekolah Tinggi Teknik Surabaya
5
» Avoid calls that will block » Precheck I/O Status ˃Will I/O block? 6 © Sekolah Tinggi Teknik Surabaya
7
8
9
10 © Sekolah Tinggi Teknik Surabaya
11 © Sekolah Tinggi Teknik Surabaya
» Poll() method ˃Takes two options: +An integer number of microseconds – May be negative to wait indefinitely – May be zero to be used as prechecking +Mode of operation – SelectRead – SelectWrite – SelectError ˃Returns true for pending operations, ready to be processed 12 © Sekolah Tinggi Teknik Surabaya
13 © Sekolah Tinggi Teknik Surabaya
» Polling is considered very inefficient » Sometimes called busy waiting » Solution: ˃Multiplexing ˃Threads ˃Asynchronous I/O 14 © Sekolah Tinggi Teknik Surabaya
» Some issues ˃Write() and Send() call blocks until last byte is written into buffer ˃Socket connection establishment will block until +Connection established +Connection refused +System-imposed timeout occurs 15 © Sekolah Tinggi Teknik Surabaya
» Example Example 16 © Sekolah Tinggi Teknik Surabaya
» Change behavior of the socket into nonblocking ˃If requested operation can be completed immediately, the calls’ return will succeed ˃ If not, it throws a SocketException with ErrorCode Catch the error, then continue… » Blocking property in Socket class » Also categorized as busy waiting technique 17 © Sekolah Tinggi Teknik Surabaya
» Example Example 18 © Sekolah Tinggi Teknik Surabaya
19
» I/O on multiple channels simultaneously » Example: echo service on several ports ˃Socket binds to a port ˃ At Accept(), which socket to choose? ˃ Accept() or Receive() may block +Use nonblocking sockets? 20 © Sekolah Tinggi Teknik Surabaya
» Socket.Select() method ˃Behavior +Specify a list of sockets to check for pending I/O +Suspends the program until one or more of the sockets in the list becomes ready to perform I/O +The list is modified to only include those Socket instances that are ready ˃Parameters +The first three: list of sockets +The fourth: time in microseconds 21 © Sekolah Tinggi Teknik Surabaya
» Example Example 22 © Sekolah Tinggi Teknik Surabaya
» David Makofske, Michael J. Donahoo, Kenneth L. Calvert, TCP/IP Sockets in C#: Practical Guide for Programmers, Morgan Kaufmann, © Sekolah Tinggi Teknik Surabaya