Java Reference
In-Depth Information
Reader reader = new InputStreamReader
(((StreamConnection) connection).openInputStream());
First, you read the new count value, denoting the number that will be assigned to the next message
arriving at the server. This value is important in order to know where to start the next request.
readLine() is a static method of this class that reads a line from the given reader:
count = Integer.parseInt (readLine (reader));
Now you read the messages submitted by the server until you reach the end of the stream:
while (true) {
String s = readLine (reader);
if (s == null || s.length() == 0) break;
addLine (s);
}
Next, you close the readers and the corresponding connection. Also, you return true in order to
indicate that the transfer was performed successfully:
reader.close();
connection.close();
return true;
}
Finally, if an exception occurred in the connection, you add the corresponding error string to the
display, and then call the disconnect() method which stops the timer that ensures the display is
updated periodically. A false value is returned in order to indicate that an exception has occurred:
catch (Exception e) {
addLine (e.toString());
disconnect();
return false;
}
}
The only other part of the application relevant for communications is RefreshTask :
class RefreshTask extends TimerTask {
public void run() {
transfer (null);
}
}
When a connection is established, it is launched with parameters to request an update of the messages
from the server every four seconds:
timer = new Timer();
timer.schedule (new RefreshTask(), 0, 4000);
Figure 6.5 shows emulated MIDP and PDAP clients connected to a local chat server. Note that the
resulting chat application is minimalistic. For example, it does not check if two different users are using
the same nickname. The application is intended to show the basic HTTP functionality only. Feel free to
extend or change the application as you like for your own purposes.
Figure 6.5. Emulated MIDP and PDAP clients connected to a local chat server.
 
 
Search WWH ::




Custom Search