Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Revision as of 05:13, 24 July 2013 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Generic Connection Framework (GCF) in Java ME.

From Wiki
Jump to: navigation, search
Article Metadata
Article
Created: senthilkumar05 (12 Dec 2007)
Last edited: hamishwillee (24 Jul 2013)

Needs-update.pngThis article needs to be updated: If you found this article useful, please fix the problems below then delete the {{ArticleNeedsUpdate}} template from the article to remove this warning.

Reasons: hamishwillee (22 Nov 2011)
Article doesn't appear to have been fully reviewed. Needs to be checked by technical expert. Formatting of code samples needs to be improved.

The GCF has the interfaces and classes to create connections such as HttpConnection, HttpsConnection ... and to perform the IO operations.

GCF has the following interfaces:

  • Connection The most basic type of connection in the GCF. All other connection types extend Connection.
  • ContentConnection Manages a connection, such as HTTP, for passing content, such as HTML or XML. Provides basic methods for inspecting the content length, encoding and type of content.
  • Datagram Acts as a container for the data passed on a Datagram Connection.
  • DatagramConnection Manages a datagram connection.
  • InputConnection Manages an input stream-based connection.
  • OutputConnection Manages an output stream-based connection.
  • StreamConnection Manages the capabilities of a stream. Combines the methods of both InputConnection and OutputConnection.
  • StreamConnectionNotifier Listens to a specific port and creates a StreamConnection as soon as activity on the port is detected.
  • Connector The Connector class is used to create instances of a connection protocol using one of Connector’s static methods. The Connector class is not designed to be instantiated. It is simply used to create instances of a connection protocol. All of the methods Connector defines are static and serve this purpose. The Connector defines three variations of an open() that return a Connection instance.
  • open(String name)
  • open(String name, int mode)
  • open(String name, int mode, boolean timeouts)

The name is essentially a URI and is composed of three parts: a scheme, an address, and a parameter list. The general form of the name parameter is as follows: <scheme>:<address>;<parameters> The mode parameter allows the connection to be established in various access modes, such as read-only, read-write and write-only. These modes are defined by the Connector constants READ, READ_WRITE, and WRITE. The timeouts parameter is a flag indicating whether or not the connection should throw an InterruptedIOException if a timeout occurs.


Supported URLs in the GCF

  • http://host:port

Make an HTTP connection to a remote server. Supported on all devices.


  • https://host:port

Make an HTTPS connection to a remote server Supported on Developer Platform 2.0 devices.


  • socket://host:port

Make a socket connection to a remote server.


  • ssl://host:port

Make a secure socket connection to a remote server.


  • socket://:port

Listen for incoming socket connections at a local port.


  • comm://IR# or nokiacomm://IR# or comm://COM#

Connect to the device's IR or serial port.


  • datagram://host:port

Send or receive UDP datagrams.

HttpConnection HTTP is the most popular data protocol of the Internet. Most wireless data networks support HTTP on top of their native wireless data carrier layers. The MIDP specification mandates support for HTTP version 1.1 on all Java handsets. We can use HTTP connections to pass both text and binary data between clients and servers.

HttpConnection hc = (HttpConnection) Connector.open("http://www.developer.nokia.com/Community/Wiki/");

HTTP data is transferred over continuous streams. Hence, the HttpConnection inherits from the StreamConnection interface. The two most important methods in HttpConnection open data streams to and from the server.

DataInputStream getDataInputStream ()
DataOutputStream getDataOutputStream ()



The HttpConnection interface supports both HTTP GET or POST operations.

In a GET operation, data is retrieved from the specified URL. We can customize the URL to pass request arguments. In this case, we only need to call the openDataInputStream() method to make the physical connection and read the data from the DataInputStream.

In a POST operation, we have to open a DataOutputStream to the specified URL first and write the request parameters to the stream. A connection is made, and the request is submitted when we close the DataOutputStream. Then we open a DataInputStream to retrieve the server response.


HttpConnection conn =
(HttpConnection) Connector.open("http://www.developer.nokia.com/Community/Wiki/");
conn.setRequestMethod(HttpConnection.GET);
 
DataInputStream din = conn.openDataInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
byte[] buf = new byte[256];
while (true) {
int rd = din.read(buf, 0, 256);
if (rd == -1) break;
bos.write(buf, 0, rd);
}
bos.flush();
buf = bos.toByteArray();
 
// Convert the byte array to string using the
// character encoding format of the remote site
String content = new String (buf, "UTF-8");



HttpsConnection

The HttpsConnection object represents a secure HTTP (HTTPS) connection. HTTPS support is mandated in MIDP 2.0 . It supports both user authentication and data encryption. The URL scheme for HttpsConnection is https://. Ex:


HttpsConnection hsc =
(HttpsConnection) Connector.open("https://secureserver.com");

The HTTPS protocol utilizes the public key infrastructure to authenticate communication parties and ensure data confidentiality once the connection is established. Digital certificates are used for authentication, and public key algorithms are used to exchange the information

SocketConnection A socket connection allows the client to communicate to specific socket ports. The URL string of SocketConnection objects takes the format of socket://host:port. The important methods in the SocketConnection interface are (i) openDataInputStream() and (ii) openDataOutputStream(), which open data streams for the client to communicate with the remote socket.

We can also specify the operation mode of the SocketConnection using the setSocketOption() method. void setSocketOption (byte option, int value) int getSocketOption (byte option

SecureConnection A SecureConnection interface extends the SocketConnection interface to add support for the Secure Socket Layer (SSL). Its URL string takes the form ssl://host:port

ServerSocketConnection The ServerSocketConnection allows us to listen for incoming connections on a socket port and essentially turns the device into a server this is not available in MIDP 1.0. Its URL string has the format of socket://:port, where the port parameter is the port number to listen to. An external device can now connect to the server device using the socket://host:port connection string, where host is the IP address of the server device. Once a ServerSocketConnection object is instantiated, we can call the acceptAndOpen() method in a loop to listen for incoming connections.


// Create the server listening socket for port 57
ServerSocketConnection scn =
(ServerSocketConnection) Connector.open("socket://:57");
 
while (true) {
// Wait for a connection
SocketConnection sc =
(SocketConnection) scn.acceptAndOpen();
 
sc.setSocketOption(RCVBUF, 128);
sc.setSocketOption(SNDBUF, 128);
 
// do something with sc
sc.close ();
}
scn.close ();



CommConnection This supports access to the device's serial port or logical serial port (e.g., the IrDA port). The URL scheme takes the form comm:port_id;params. The port_id is COM# for RS232 serial ports and IR# for IrDA ports. For example, the URL string comm:IR0;baudrate=19200 opens a connection to the first infrared port with a 19,200 bit per second data rate.


UDPDatagramConnection The datagram protocol directly passes data packets between endpoints without trying to assemble them to match their originating order or recover lost data. The datagram arrival order or even the delivery itself is not guaranteed. It is, however, often faster and more suitable for real-time applications.

The UDPDatagramConnection interface inherits from the DatagramConnection interface. The URL string is datagram://host:port. It cannot open data streams but has methods to support composing, sending, and receiving datagrams.


Datagram newDatagram(int i)
Datagram newDatagram(int i, String s)
Datagram newDatagram(byte[] bytes, int i)
Datagram newDatagram(byte[] bytes, int i, String s)
void send(Datagram datagram)
void receive(Datagram datagram)
/*
* Network Example
*/

 
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.util.*;
import java.io.*;
 
public class NetEg extends MIDlet {
 
private static Command httpTestCommand = new Command("HttpConn", Command.SCREEN, 1);
private static Command datagramSendCommand = new Command("Send Datagram", Command.SCREEN, 1);
private static Command datagramReceiveCommand = new Command("Receive Datagram", Command.SCREEN, 1);
private static Command socketClientCommand = new Command("Socket Client", Command.SCREEN, 1);
private static Command socketServerCommand = new Command("Socket Server", Command.SCREEN, 1);
private Command commandType;
 
private List list = new List("Http Test", List.IMPLICIT);
 
/**
Used to create instances of the MIDlet
*/

public NetEg()
{
CommandListener listener = initListeners();
Display.getDisplay(this).setCurrent(list);
list.addCommand(httpTestCommand);
list.addCommand(datagramSendCommand);
list.addCommand(datagramReceiveCommand);
list.addCommand(socketClientCommand);
list.addCommand(socketServerCommand);
list.setCommandListener(listener);
}
 
/**
Used to create instances of Thread to run the actual command
*/

public NetEg(Command cmd)
{
commandType = cmd;
}
 
public void startApp()
{
}
 
public void pauseApp()
{
}
 
public void destroyApp(boolean unc)
{
}
 
private void appendData(String data)
{
list.append(data, null);
}
 
/**
Create a listener command handler
*/

private CommandListener initListeners()
{
return new CommandListener()
{
public void commandAction(Command command, Displayable displayable)
{
Thread t = new Thread(new CommandHandler(command));
t.start();
}
>};
}
 
class CommandHandler implements Runnable
{
private Command commandType;
 
public CommandHandler(Command type)
{
commandType = type;
}
 
 
private void httpTest()
{
 
HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
try
{
c = (HttpConnection)Connector.open("<nowiki>http://localhost</nowiki>", Connector.READ_WRITE, true);
c.setRequestMethod(HttpConnection.GET); //default
is = c.openInputStream(); // transition to connected!
int ch = 0;
for(int ccnt=0; ccnt &lt; 150; ccnt++) //get the title.
{
ch = is.read();
System.out.print((char)ch);
if (ch == -1)
{<br>break;<br>}<br>sb.append((char)ch);
}<br>}<br>catch (IOException x)
{<br>x.printStackTrace();
}
finally
{
try
{
is.close();
c.close();
} catch (IOException x)
{
x.printStackTrace();
}
}
appendData(sb.toString());
}
 
private void sendDatagram()
{
try
{
DatagramConnection dgc = (DatagramConnection) Connector.open("datagram://localhost:9001");
try
{
byte[] payload = "Hello from a Datagram".getBytes();<br>Datagram datagram = dgc.newDatagram(payload, payload.length);
dgc.send(datagram);
} finally
{
dgc.close();
}
} catch (IOException x)
{
x.printStackTrace();
}
}
 
private void receiveDatagram()
{
try
{
DatagramConnection dgc = (DatagramConnection) Connector.open("datagram://:9001");
try
{
int size = 100;
Datagram datagram = dgc.newDatagram(size);
dgc.receive(datagram);
appendData(new String(datagram.getData()).trim());
} finally
{
dgc.close();
}
} catch (IOException x)
{
x.printStackTrace();
}
}
 
private void clientSocket()
{
try
{
SocketConnection sc = (SocketConnection) Connector.open("socket://localhost:9002");<br>OutputStream os = null;<br>try<br>{<br>os = sc.openOutputStream();
byte[] data = "Hello from a socket!".getBytes();
os.write(data);
} finally
{
sc.close();
os.close();
}
} catch (IOException x)
{
x.printStackTrace();
}
}
 
private void serverSocket()
{
try
{
ServerSocketConnection ssc = (ServerSocketConnection) Connector.open("socket://:9002");
StreamConnection sc = null;
InputStream is = null;
try
{
sc = ssc.acceptAndOpen();
is = sc.openInputStream();
System.out.println("connection opened!");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1)
{
sb.append((char)ch);
}
appendData(sb.toString());
} finally
{ssc.close();
sc.close();
is.close();
}
} catch (IOException x)
{
x.printStackTrace();
}
}
 
public void run()
{
System.out.println("Running Command");
 
if (commandType == httpTestCommand)
{
httpTest();
} else if (commandType == datagramSendCommand)
{<br>sendDatagram();
} else if (commandType == datagramReceiveCommand)
{
receiveDatagram();
} else if (commandType == socketClientCommand)
{
clientSocket();
} else if (commandType == socketServerCommand)
{
serverSocket();
}
else
{
throw new IllegalStateException("No command specified to run.");
}
}
}
}
This page was last modified on 24 July 2013, at 05:13.
98 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×