Monday, January 17, 2011

Non-blocking Network I/O and Timeout in BlackBerry API

Currently I am working on porting a C++ project to BlackBerry JDE 5.0. In the C++ implementation of the project, I have noticed use of select() function to enforce timeout property in C++ socket programming. I had to find non-blocking network I/O API in BlackBerry JDE 5.0 documentation but to no avail. As klyubin pointed out, no non-blocking I/O API is present on BlackBerry. He suggested two solutions: (1) setting a read/write timeout on the connection (which is not supported on some old platforms) and (2) periodically checking some timeout value from another thread (e.g., daemon thread, Timer, event dispatcher) and disconnect once the timeout expires.

The first solution seemed faster to integrate. So I searched and found the following:

For UDP connection, use DatagramConnectionBase.

DatagramConnectionBase connection = (DatagramConnectionBase) Connector.open(connectionString, mode, true); // 3rd argument : timeout is enabled
connection.setTimeout(10000); // 10 seconds


For TCP connection, use SocketConnectionEnhanced as pointed out by Mark Sohm.

For TCP connection through BES (BlackBerry Enterprise Server), the following BlackBerry Knowledge Base article is useful:
How To - Control the connection timeout for TCP connections through the BlackBerry MDS Connection Service