j2me 의 General File Connection 프레임웍에 사용예..
출처 : http://www.devx.com/wireless/Article/21871/0/page/1
Figure 1. The J2ME Stack: The configuration layer forms the basis for the J2ME stack and defines the characteristics of the J2ME. |
In order to make the GCF available to all J2ME application profiles, the GCF is implemented in the configuration layer. The configuration layer is a set of J2ME libraries that form the basis of any J2ME architecture. Packages such as java.lang, java.util, java.io, and so forth can be found in the configuration layer. Figure 1 shows how the configuration layer relates to the profile layer in J2ME
Currently, there are two J2ME configurations that support networking: the Connected Limited Device Configuration (CLDC) and the Connected Device Configuration (CDC). The CLDC is designed for more limited devices that require a smaller API footprint. MIDP is based on the CLDC. The CDC is designed for devices with more power and API footprint but are still too small to support standard Java. The Personal Profile is based on the CDC.
In order to enhance the upward compatibility of J2ME applications from the CLDC range of devices to the CDC range of devices, the CLDC and CDC have a strict superset-subset relationship. Figure 2 shows the relationship between the CLDC, CDC, and J2SE. Note that the CLDC and CDC contain APIs that are unique to J2ME and not part of standard Java. Libraries that are unique to J2ME exist in the javax.microedition.* packages.
Figure 2. Concentric Circles. The CDC and CLDC have a strict subset-superset relationship. Note also that J2ME configurations contain APIs that extend beyond what standard Java (J2SE) provides. |
Configurations and Connectivity
The GCF is implemented in the CLDC, thereby making it available to any J2ME application since, by definition, the CDC must include everything defined by the CDLC. This has the effect of standardizing network connectivity throughout the J2ME environment, regardless of the profile or the device—a big advantage for J2ME developers.
Creating Network Connections using the GCF
Before discussing the architecture any further, I want to look at some code. At the heart of the GCF is the Connector class and a set of interfaces that are defined in the javax.microedition.io package. The Connector class is a factory that creates connection instances. The interfaces define the types of connections supported. How the implementer actually provides the network connectivity is not of concern, to either the GCF or the application developer, as long as the connection returned supports the behaviors defined by the GCF interface. An example of an HTTP connection is shown below.
HttpConnection c = (HttpConnection)
Connector.open("http://www.gearworks.com",
Connector.READ_WRITE, true);
The Connector class figures out what type of connection to create by parsing the connection string ("http://www.gearworks.com" in this case). The connection string is composed of three parts: the scheme, target, and parameters. The scheme is required but the latter two are optional. All connection strings follow the pattern noted below.
{scheme}: [{target}] [{parameters}]
In the HTTP example the scheme is "http" and the target is "www.gearworks.com." There are no parameters.
Although the connection string looks a lot like a URL, it can be used to create many different types of connections, not just HTTP connections. Table 1 shows examples of different types of connections that may be created using the GCF. Note however, the actual support for a specific connection is subject to the J2ME profile requirements and what a vendor chooses to implement. If the connection is not supported by the J2ME implementation a ConnectionNotFoundException is thrown.
HTTP | http://www.host.com: 8080 |
Socket | socket://host.com:80 |
Socket Listener | socket://:1234 |
Datagram Sender | datagram://host.com:9001 |
Datagram Listener | datagram://: 9001 |
File | file:/myfile.txt |
Comm Port | comm:com0;baudrate=19200;parity=odd |
Table 1. Examples of different types of connections that may be created using the GCF. Support for the actual connection type, however, is implementation dependent.
It is quite possible for someone to have worked with Java for some time without ever needing to understand or use datagrams. For mobile devices, however, datagrams offer some advantages in that they are rather lightweight when compared to TCP-based connections such as sockets. User Datagram Protocol, UDP, is one of the more common datagram protocols. However, because most datagram protocols follow the same basic principals as to their usage, the GCF is able to support datagrams generically.
Using Datagrams
The following example shows how to create a datagram and send it to a specific IP address.
try {
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://localhost:9001");
try {
byte[] payload = "Test Message".getBytes();
Datagram datagram =
dgc.newDatagram(payload, payload.length);
dgc.send(datagram);
} finally {
dgc.close();
}
} catch (IOException x) {
x.printStackTrace();
}
Next I show how an application might receive the datagram sent by the previous code snippet.
try {
DatagramConnection dgc = (DatagramConnection)
Connector.open("datagram://:9001");
try {
int size = 100;
Datagram datagram = dgc.newDatagram(size);
dgc.receive(datagram);
System.out.println(
new String(datagram.getData()).trim());
} finally {
dgc.close();
}
} catch (IOException x){
x.printStackTrace();
}
In order to run the send and the receive examples, two instances of a MIDlet can be run from the Wireless Toolkit, one to perform the receive and one to perform the send.
Socket To Me
Another type of connection commonly available on J2ME devices is the TCP-based socket connection. Sockets are different than datagrams because they use a connection-based paradigm to transmit data. This means that both a sender and a receiver must be running and establish a communication channel for data to be exchanged. To use a real-world analogy, a socket connection is like calling a friend on the telephone. If the friend does not answer, a conversation cannot take place. Datagrams on the other hand are more like sending a letter to a friend, where a note is placed into an envelope, addressed, and mailed.
The following code demonstrates how to set up a listener to monitor a port for an inbound socket connection.
try { ServerSocketConnection ssc = (ServerSocketConnection) Connector.open("socket://:9002"); StreamConnection sc = null; InputStream is = null; try{ sc = ssc.acceptAndOpen(); is = sc.openInputStream(); int ch = 0; StringBuffer sb = new StringBuffer(); while ((ch = is.read()) != -1){ sb.append((char)ch); } System.out.println(sb.toString()); } finally{ ssc.close(); sc.close(); is.close(); } } catch (IOException x) { x.printStackTrace(); }
The next example demonstrates the code required by the client to initiate the socket connection.
try{
SocketConnection sc = (SocketConnection)
Connector.open("socket://localhost:9002");
OutputStream os = null;
try{
os = sc.openOutputStream();
byte[] data = "Hello from a socket!".getBytes();
os.write(data);
} finally{
sc.close();
os.close();
}
} catch (IOException x){
x.printStackTrace();
}
Reading Web Content
The last example will cover reading data using the MIDP HttpConnection. Note that this connection interface is not part of the CLDC or CDC, but is defined rather in the MIDP and Personal Profiles themselves. The behavior of HttpConnection is one that combines an InputStream and an OutputStream into a single connection. A single HttpConnection may open and use exactly one OutputStream and exactly one InputStream. The order in which the streams are used is important as well. The OutputStream, if used, must be used before the InputStream. Once the streams have been used the connection should be closed and a new HttpConnection should be opened to continue communications if necessary. This follows the HTTP request-response paradigm.
The HttpConnection is a bit more tricky to use than the socket or datagram connections because there is a lot that happens behind the scenes. There are three states to an HttpConnection:
- Setup
- Connected
- Closed
The transition from setup to connected is triggered by any methods that cause data to be sent to the server. The following is a list of methods that cause this transition.
- openInputStream
- openDataInputStream
- getLength
- getType
- getEncoding
- getHeaderField
- getResponseCode
- getResponseMessage
- getHeaderFieldInt
- getHeaderFieldDate
- getExpiration
- getDate
- getLastModified
- getHeaderField
- getHeaderFieldKey
HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
try {
c = (HttpConnection)Connector.open(
"http://www.gearworks.com”,
Connector.READ_WRITE, true);
c.setRequestMethod(HttpConnection.GET); //default
is = c.openInputStream(); // transition to connected!
int ch = 0;
for(int ccnt=0; ccnt < 150; ccnt++) { // get the title.
ch = is.read();
if (ch == -1){
break;
}
sb.append((char)ch);
}
}
catch (IOException x){
x.printStackTrace();
}
finally{
try {
is.close();
c.close();
} catch (IOException x){
x.printStackTrace();
}
}
System.out.println(sb.toString());
In this example, the server at www.gearworks.com is contacted. Because this is an HttpConnection and no port is specified, port 80 is used by default. The request method is set to GET (note GET is the default and is explicitly set here only for the example).
As I've just explained, the GCF makes a number of networking options available to applications, but there are a few things you need to know in order to decide which to use when. In the case of MIDP, the specification only requires support for HTTP, although many devices support datagrams and sockets as well, because these protocols are needed to implement HTTP. However, before making commitments to datagrams or sockets it is a good idea to make sure they are supported on the platforms you are targeting. Because HTTP is guaranteed to be supported by MIDP this is usually the best protocol choice due to portability. HTTP moves through firewalls easily since it generally operates over port 80. However, of the three protocols discussed, HTTP incurs the most overhead, which may drive up the user's cost of using the application on the network.
Datagrams, on the other hand, tend to have far less overhead and can be easier on the end-user's budget. The caveat, as discussed previously, is that the application must take on the task of ensuring that all data arrived at the other end and that the order of that data received is correct.
Finally, sockets fall somewhere in the middle of HTTP and datagrams in that data sent over a socket is managed by the protocol, but requires fewer network resources than HTTP. This means that the application does not have to concern itself with making sure data is received on the other end. Sockets are generally a lighter-weight option over HTTP since the application controls when the end points communicate. HTTP, on the other hand, must make several trips between the end points to exchange header information as well as the data.
The GCF provides a lot of functionality and standardizes how connections are established throughout the J2ME architecture. The GCF is extensible as well, allowing manufacturers to support their own interfaces and connection types. In some cases a manufacturer may use the GCF to support streaming multimedia content with a special connection or for establishing connections to a GPS receiver. Having this kind of flexibility prevents J2ME from being constrained to a common set of protocols while maintaining consistency throughout the architecture.
'j2me' 카테고리의 다른 글
[본문 스크랩] [Java Wireless] MIDP 2.0 보안 아키텍처의 이해 (0) | 2006.02.21 |
---|---|
Java on PocketPC, the Unofficial FAQ (0) | 2006.02.07 |
노키아의 MIDP System Properties (0) | 2006.02.03 |
J2me properties (0) | 2006.02.03 |
[펌] 10. GCF 프로그래밍(1) (0) | 2005.12.04 |