Java Reference
In-Depth Information
raw positioning data read from a GPS receiver using a serial connection. An input line allows you to
send data over the connection.
Here, we will only describe the network related parts of the application. The complete sources of the
PdapTerminal
application user interfaces consist of a widget in which you can enter a URL that is
used to open a particular connection. The connection is established by activating the
Connect
command or by pressing the
Connect
button, depending on the platform in which the application is
running.
The core of the Terminal implementation is contained in an inner class of the main application called
Handler
. This class "handles" establishing the connection and receiving new data in the background.
For that purpose, the
Handler
stores the connection, as well as the corresponding input and output
streams in member variables. It also contains a variable
leave
that determines whether the handler
should leave the receive loop and terminate itself:
class Handler extends Thread {
StreamConnection connection;
InputStream in;
OutputStream out;
boolean leave;
The constructor of the
Handler
takes a URL as input and establishes a corresponding stream
connection. It is called from the main application when the user enters an address and requests a
corresponding connection. The
Handler
is not able to handle datagram or serversocket protocols.
Trying to do so would cause a class cast exception.
When the connection is established, the
out
and
in
variables are set. Then, the establishment of the
connection is reported using the
show()
method of the main class:
public Handler (String url) throws IOException {
connection = (StreamConnection) Connector.open
(url, Connector.READ_WRITE, true);
out = connection.openOutputStream();
in = connection.openInputStream();
show ("opened: "+ url + "\r");
}
The main work is performed in the
run()
method of the
Handler
thread. The
run()
method is
invoked automatically when the main application calls the
start()
method, which runs the handler
as a separate thread in the background. In the
run()
method, incoming data is collected in a string
buffer until the leave flag is set, no more data is available, or the buffered data reaches a limit of 1024
bytes. In that case, the collected data is shown to the user by handing it over to the
show()
method.
Then, the buffer is cleared and a new iteration of the read loop is entered. If read encounters a
-1
, that
means that the stream is closed remotely. In that case,
disconnect()
is called in order to terminate
the
Handler
and to release the connection:
public void run() {
StringBuffer buf = new StringBuffer();
try {
while (!leave) {
Search WWH ::
Custom Search