⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mar02_ericg.txt

📁 TechTips j2me的常用技巧. 网络功能
💻 TXT
📖 第 1 页 / 共 3 页
字号:

            try {
                conn = (HttpConnection)
                           Connector.open( url );
                conn.setRequestMethod( conn.POST );
                conn.setRequestProperty( 
                          "Content-Type", 
                          "application/octet-stream" );
                conn.setRequestProperty( "User-Agent",
           "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
                conn.setRequestProperty( 
                     "Content-Length",
                     Integer.toString( record != null ?
                                record.length : 0 ) );

                OutputStream os =
                                conn.openOutputStream();
                if( record != null ){
                    os.write( record );
                }
                os.close();

                int rc = conn.getResponseCode();
                if( rc == HttpConnection.HTTP_OK ){
                    if( recordID != 0 ){
                        try {
                            outrs.deleteRecord( 
                                           recordID );
                        }
                        catch( 
                             RecordStoreException e ){
                        }
                    }
                }
            }
            catch( IOException e ){
                if( record != null ){
                    try {
                        outrs.setRecord( recordID, 
                            record, 0, record.length );
                    }
                    catch( RecordStoreException re ){
                    }
                }

                conn = closeConnection( conn );
            }

            recordID = 0;
            record = null;
            checkForMore = false;

            // Third stage: if the POST was successful,
            // read in an incoming record, if any.

            if( conn != null ){
                DataInputStream is = null;

                try {
                    int len = (int) conn.getLength();
                    if( len > 0 ){
                        record = new byte[ len ];
                        is = conn.openDataInputStream();
                        is.readFully( record );
                        checkForMore = true;
                    }
                }
                catch( IOException e ){
                    record = null;
                }
                finally {
                    if( is != null ){
                        try {
                            is.close();
                        }
                        catch( IOException e ){
                        }
                    }
                }
            }

            conn = closeConnection( conn );

            // Fourth stage: write out the new message
            // and notify a waiting thread.

            if( record != null ){
                synchronized( inrs ){
                    try {
                        inrs.addRecord( record, 0,
                                    record.length );
                        inrs.notify();
                    }
                    catch( RecordStoreException re ){
                    }
                }
            }
        }

        // Some cleanup code

        synchronized( this ){
            if( thread == Thread.currentThread() ){
                thread = null;
            }
        }
    }

    // Starts the background thread.

    public synchronized void start() {
        if( thread == null ){
            thread = new Thread( this );
            thread.start();
        }
    }

    // Stops the background thread.

    public synchronized void stop(){
        if( thread != null ){
            Thread tmp = thread;
            thread = null;

            try {
                tmp.join();
            }
            catch( InterruptedException e ){
            }
        }
    }

    // Cleanup by waiting for the thread to
    // stop and then closing the record stores.

    public synchronized void destroy(){
        stop();

        synchronized( outrs ){
            try {
                outrs.closeRecordStore();
            }
            catch( RecordStoreException e ){
            }

            outrs.notifyAll();
        }

        synchronized( inrs ){
            try {
                inrs.closeRecordStore();
            }
            catch( RecordStoreException e ){
            }

            inrs.notifyAll();
        }
    }

    private RecordStore inrs;
    private RecordStore outrs;
    private Thread      thread;
    private String      url;
    private int         pullTimeout;
}

As mentioned earlier, two MIDP record stores are associated with 
the hub. One holds the outgoing messages, and the other holds 
incoming messages. These provide the persistent storage required 
to build a reliable store-and-forward messaging system. The send 
method in the hub serializes a message and adds it to the 
outgoing record store. The receive method removes a message from
the incoming record store and deserializes it.

The real work is done by the hub's background thread in the run 
method. Whenever a message is added to the outgoing record store, 
or a polling timeout expires, the background thread wakes up and 
sends a POST request to the servlet, sending a message (if 
available) as part of the request body. The servlet can respond 
with a simple status or with a message to deliver to the client.
The background thread then adds the message to the incoming 
record store and wakes a waiting thread.

The servlet code itself is quite simple when compared to the hub:

import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * A simple servlet that receives a message
 * from a client and immediately sends one back. 
 */

public class MessagingServlet extends HttpServlet {

    private static int counter = 0;

    public void doPost( HttpServletRequest request,
                        HttpServletResponse response )
            throws IOException, ServletException {

        SimpleMessage msg = null;
        byte[]        rawdata = null;
        Object        received = null;

    // Read the incoming message, if any...

        int len = request.getContentLength();
        if( len > 0 ){
            ServletInputStream in = 
                     request.getInputStream();
            DataInputStream    din = 
                     new DataInputStream( in );

            rawdata = new byte[ len ];
            din.readFully( rawdata );

            try {
                msg = new SimpleMessage();
                msg.resurrect( rawdata );
                received = msg.getData();
            }
            catch( IOException e ){
            }

            din.close();
        }

        rawdata = null;

        // Send a canned response for any 
        // incoming message

        if( received != null ){
            ++counter;
    
            msg = new SimpleMessage();
            msg.setDestination( "client" );
            msg.setData( "Counter: " + counter + 
               " Date: " + new Date().toString() + 
               " Received: " + received );
    
            try {
                rawdata = msg.persist();
            }
            catch( IOException e ){
                rawdata = null;
            }
        }

        // Send it out!

        response.setContentType( 
             "application/octect-stream" );
        response.setContentLength( 
             rawdata != null ? rawdata.length : 0 );
        response.setStatus( response.SC_OK );

        if( rawdata != null ){
            OutputStream out = 
                     response.getOutputStream();
            out.write( rawdata );
            out.close();
        }
    }
}

This servlet is just a test servlet. All it does is generate 
a response for each message it receives. Normally, you'd have the
servlet convert the messages to and from JMS, or something more 
meaningful.

Finally, here is a very simple MIDlet to test the message hub's 
interaction with the test servlet:

import java.io.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;

// A very simple MIDlet to test out the message hub.
// Doesn't create any UI, just prints messages out
// to the console.

public class MessagingTest extends MIDlet
                 implements CommandListener {

    private Display    display;
    private MessageHub hub;

    public static final Command exitCommand =
                         new Command( "Exit",
                                     Command.EXIT, 1 ); 

    public MessagingTest(){
    }

    public void commandAction( Command c,
                               Displayable d ){
        if( c == exitCommand ){
            exitMIDlet();
        }
    }

    protected void destroyApp( boolean unconditional )
                    throws MIDletStateChangeException {
        exitMIDlet();
    }

    public void exitMIDlet(){
        if( hub != null ){
            hub.destroy();
        }

        notifyDestroyed();
    }

    public Display getDisplay(){ return display; }

    protected void initMIDlet(){
        try {
            testHub();
        }
        catch( Exception e ){
            System.err.println( "Exception " + e );
        }

        exitMIDlet();
    }

    protected void pauseApp(){
    }

    protected void startApp()
                    throws MIDletStateChangeException {
        if( display == null ){ 
            display = Display.getDisplay( this );
            initMIDlet();
        }
    }

    private void log( String str ){
        System.out.println( str );
    }

    private static final String TEST_URL =
             "http://localhost:8080/MessagingServlet";

    private static final int PULL_TIMEOUT = 5000;

    // The code to test the hub. Sends ten messages
    // and then reads the replies.

    private void testHub() throws IOException,
                                 RecordStoreException {
        log( "Creating hub to " + TEST_URL );

        hub = new MessageHub( 
                              TEST_URL, PULL_TIMEOUT );

        log( "Starting hub..." );
        hub.start();

        log( "Sending ten messages to server..." );
        for( int i = 1; i <= 10; ++i ){
            SimpleMessage msg =
               new SimpleMessage( "serverUserID",
                     "Client message " + i );

            log( "Sending " + msg + "..." );
            hub.send( msg );
            log( "...sent" );
        }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -