SocketConnection is a basic StreamConnection for network communications. It works much like HttpConnection. However, it has no particular understanding of HTTP or any other protocol. It just opens a standard TCP socket to a specified host and relies on your code to tell it what to do with the input and output from that host.
Socket URLs look like this:
socket://server.example.com:13
This indicates a TCP connection to server.example.com on port 13.
Opening SocketConnection is straightforward and works much like opening any other sort of connection:
Connection connection = Connector.open("socket://rama.poly.edu:13");
If you don need to set any special socket options, you can use one of the four open stream methods, and proceed as you would with any other connection. Example 24-1 used the socket protocol.
Most of the time thats all you need. However, SocketConnection does have six unique methods of its own. To use these, you must first cast the connection object returned by open( ) to SocketConnection:
SocketConnection socket = (SocketConnection) connection;
First, there are four getter methods that return the address and port of the remote and local hosts the socket connects:
public String getAddress( ) throws IOException public int getPort( ) throws IOException public int getLocalPort( ) throws IOException public String getLocalAddress( ) throws IOException
J2ME doesn include the InetAddress class, so the host addresses are all returned as strings like "192.168.254.100" or "FEDC::DC:0:7076:10". Theres no method to get the hostname, because devices where J2ME runs are unlikely to have hostnames.
These methods all throw an IOException if the socket has been closed.
J2ME devices often have different network characteristics than typical desktop and server systems. They may have very limited, unreliable, or sporadic bandwidth. As a result, it may be important to change socket options to better fit the characteristics of the network. The getSocketOption( ) and setSocketOption( ) methods enable this:
public void setSocketOption(byte option, int value) throws IllegalArgumentException, IOException public int getSocketOption(byte option) throws IllegalArgumentException, IOException
Socket options must be set before the socket is connected; that is, before you ask a connection for its input or output stream.
J2ME recognizes five socket options, each referenced as a named constant in the SocketConnection class:
SocketConnection.DELAY
Nonzero to enable Nagles algorithm; zero to disable Nagles algorithm
SocketConnection.LINGER
Number of seconds to wait before closing a connection with pending data to write
SocketConnection.KEEPALIVE
Nonzero to enable keepalive; zero to disable keepalive
SocketConnection.SNDBUF
Size in bytes of the send buffer
SocketConnection.RCVBUF
Size in bytes of the receive buffer
Picking an option not in this list throws an IllegalArgumentException.