Java Reference
In-Depth Information
try {
c = (StreamConnection)Connector.open(url);
s = c.openInputStream();
o = c.openOutputStream();
o.write("Hello world!".getBytes());
s.read( b, 0, b.length );
} catch (ConnectionNotFoundException e) {...}
catch (IllegalArgumentException e) {...}
catch (IOException ioe) {...}
finally {
try {
if (o != null) o.close();
if (s != null) s.close();
if (c != null) c.close();
} catch (Exception e) {...}
}
This code opens a TCP socket to port 7—the echo port—and proceeds to write the
message “Hello world!” Once it writes the message, it reads the response and then tears
down the streams and connection. As you see from the code, you perform the actual
I/O using the input and output stream classes InputStream and OutputStream ; they let
you exchange individual arrays of bytes using their read and write methods. For higher-
level access, you can also obtain DataInputStream and DataOutputStream instances from
the connection using the StreamConnection 's methods openDataInputStream and
openDataOutputStream ; as you recall from Chapter 2, they let you read and write primi-
tive data types including floating-point numbers, integers, and strings.
The SocketConnection instance that Connector.open returns has a few more methods
than the StreamConnection , and it lets you perform some low-level operations on the
socket by invoking the following methods:
getAddress : Lets you obtain the remote address to which the socket is bound by
invoking on the socket
getLocalAddress : Lets you obtain the local address to which the socket is bound
getPort : Lets you obtain the remote port to which the socket is bound
getLocalPort : Lets you obtain the local port to which the socket is bound
getSocketOption : Lets you get a socket option
setSocketOption : Lets you set a socket option
 
Search WWH ::




Custom Search