in
Development J2ME networking application introduces how to connect through the HTTP protocol, usually we call the Advanced Network through the HTTP network. In this article, we tell how to use Socket on the TCP / IP layer. If you still don't know the General Networking framework of the J2ME platform, please refer to
Introduce the J2ME Universal Networking framework.
TCP / IP and UDP support TCP / IP and UDP are provided in MIDP 2.0. javax.microedition.io.SocketConnectionjavax.microedition.io.ServerSocketConnectionjavax.microedition.io.UDPDatagramConnection today focuses on the use of SocketConnection and TCP / IP client server communication, the latter two categories will be covered in a future article, defined SocketConnection Socket stream connection. Call Connector.Open ("socket: // host: port") will return an instance of a socketconnection. By calling socket.openputStream () and socket.OpenOutputStream (), we will get an instance of InputStream and OutputStream so that we can communicate with the server, as shown below: SocketConnection Client = (socketconnection) Connector.Open (" socket: // " hostname ": " port); client.setSocketOption (DELAY, 0); client.setSocketOption (KEEPALIVE, 0); InputStream is = client.openInputStream (); OutputStream os = client.openOutputStream () Os.write ("Some String" .GetBytes ()); int C = 0; while ((c = is.read ())! = -1) {// do something sTHING with the response} is.close () os.close (); client.close ();
Note that when we are connected, we must also have network operations in another thread without the main thread. Such aim is to avoid clogging of the user interface. Usually we can define a class extension Thread class and provide a constructor that uses the MIDlet as a parameter. In order to improve the efficiency, we use the wait () and notify () methods, only when the user presses the button, the thread is awakened. Perform the networking operation, otherwise he has been going out to "Wait" after startup. Class Commandthread Extends Thread {MIDlet PARENT;
StreamConnection Socket = NULL; InputStream IS = NULL;
Boolean EXIT = FALSE;
Public Commandthread (MIDlet Parent) {this.parent = Parent;
Public void Run () {while (! "{while (!" {parent.wait ();} catch (interruptedExcection) {}}} ......... .............................. TCP / IP server is the same as the general server writing, so no more Introduce. If you have any questions, you can refer to the contents of the java.net package. By the example demonstrates, we build a time server, access to the Socket, and get the current time displayed on the screen. The code is as follows: import java.io.bufferedoutputstream; import java.io.DataOutputStream; import java.io.ioException; import java.net.socket; import java.Net.Serversocket; import java.util.date;
Public class daytimeserver {
Public static void main (string args []) {
INT daytimeport = 13;
IF (args.length == 1) {try {daytimeport = integer.parseint (args [0]);} catch (NumberFormatexcection E) {system.out.println ("Invalid Port Number"); System.exit (0) }}
Serversocket Serversocket = NULL; Socket SOCK;
Dataoutputstream Data;
Try {serversocket = new serversocket;} catch (ioException e) {system.out.println (E.GETMESSAGE ()); E.PrintStackTrace (); system.exit (0);}
while (true) {try {sock = serverSocket.accept (); dataout = new DataOutputStream (new BufferedOutputStream (sock.getOutputStream ())); String dateString = new Date () toString ();. dataout.write (dateString.getBytes (), 0, DateString.Length ()); DataOut.flush (); sock.close ();} catch (ieException e) {system.out.println (E.GETMESSAGE ()); E.PrintStackTrace (); }}}}
import javax.microedition.midlet *;. import javax.microedition.lcdui *;. import java.io *;. import javax.microedition.io *;. public class DayTimeClient extends javax.microedition.midlet.MIDlet implements CommandListener {
Display display;
Private Boolean CommandAvailable; Commandthread Commandthread; List Menu; Form OutputForm; StringItem Dt; Command Cmdback; Command Cmdexit;
Private static final string protocol = "socket:"; private string daytimearch;
public void startApp () {String host = getAppProperty ( "HOST"); String port = getAppProperty ( "DAYTIME_PORT"); try {(Integer.parseInt (port));} catch (NumberFormatException e) {destroyApp (false); notifyDestroyed (); DAYTIMEURL = Protocol "//" Host ":" port; display = display.getdisplay (this); outputform = new form ("DATE / TIME"); DT = New StringItem (null, null ); Outputform.Append (DT); cmdback = new Command ("back", command.back, 1); Outputform.Addcommand (cmdback); cmdexit = new command ("exit", command.exit, 1); OutputForm. Addcommand (cmdexit); OutputForm.SetCommandListener (this);
Menu = New List ("Menu", List.Implicit; Menu.Append ("Get Date / Time", NULL); Menu.Append ("EXIT", NULL); Menu.setCommandListener (this); Display.SetCurrent Menu;
CommandAvailable = false; commandthread = new commandthread (this); commandthread.start ();
Public void pauseapp () {}
Public void destroyApp (boolean unconditional) {}
Public void CommandAction (Command CMD, Displayable D) {IF (cmd == cmdexit) {destroyApp (false); notifyDestroyed ();} else if (cmd == cmdback) {Display.setCurrent (MENU);} else IF D == MENU) && (cmd == list.select_command) {synchroIzed (this) {commandavailable = true; notify ();}}} class commandthread extends thread {midlet parent;
StreamConnection Socket = NULL; InputStream IS = NULL;
Boolean EXIT = FALSE;
Public Commandthread (MIDlet Parent) {this.parent = Parent;
public void run () {while (exit!) {synchronized (parent) {while {try {parent.wait () (commandAvailable!);} catch (InterruptedException e) {}}} commandAvailable = false; switch (menu.getSelectedIndex ()) {Case 0: getdate (); break; case 1: exit = true;}} design; notifydestroyed ();
Public void getdate () {Try {socket = (streamconnection) connector.open (daytimeurl, connector.read, true);
IS = Socket.openInputStream ();} catch (exception e) {}
Try {int b; stringbuffer sb = new stringbuffer (); while ((b = is.read ())! = -1) {sb.append ((char) b);} Socket.close (); dt.setText (sb.toString ()); Display.SetCurrent (Outputform);} catch (exception e) {}}}} You need to define two attribute values in the JAD file, of course, you can also write DAYTIME_PORT directly in the source code: 13Host: 127.0.0.1