`

Applet + Javascript 替代 comet 轮回 pull

    博客分类:
  • JAVA
阅读更多
对于不熟悉flex的童鞋,要做一些像聊天等交互性功能,用applet + js也是很容易实现的——而且,跨浏览器,js也容易操作dom进行页面内容展示。



1. 建立一个工程,compiler level设置1.3

2. 找到jre lib 下的plugin.jar,导入路径

3. 写一个比较通用的socket client applet,暴露一些主要方法,比如jsFunCall connect close send,connect方法里开启一个domain thread负责接收处理数据(最好是以接口形式)



话说actionscript那种socket方法回调那是一个简单啊!java线程小麻烦了点。

package com.cisee.appletjs;   
  
import java.applet.Applet;   
import java.io.IOException;   
import java.io.InputStream;   
import java.io.OutputStream;   
import java.net.Socket;   
import java.util.Random;   
  
import netscape.javascript.JSException;   
import netscape.javascript.JSObject;   
  
public abstract class JsApplet extends Applet {   
  
    /** Socket */  
    private Socket sock = null;   
    /** Input Stream */  
    private InputStream is = null;   
    /** Output Stream */  
    private OutputStream os = null;   
       
    private final int port = 12800;   
    private final String host = "127.0.0.1";   
  
    /** win JSObject */  
    protected JSObject win = null;   
    /** doc JSObject */  
    protected JSObject doc = null;   
  
    /** Is connected? */  
    protected boolean connected = false;   
       
    Thread reviever;   
       
    String userid;   
    String toUserid;   
  
    protected String getInfo() {   
        return "Cisee Applet Javascript Interpretor Operation";   
    }   
  
    public void init() {   
        logMsg("Init..");   
        userid = System.currentTimeMillis() + "_" + new Random().nextInt(100);   
    }   
  
    public void destroy() {   
        closeConnect();   
    }   
  
    /**  
     * JS Object   
     */  
    protected JSObject getWin() {   
        if (win == null)   
            win = JSObject.getWindow(this);   
        return win;   
    }   
  
    protected JSObject getDoc() {   
        if (doc == null)   
            doc = (JSObject) getWin().getMember("document");   
        return doc;   
    }   
  
    public abstract void processMessage(final String msg);   
  
    /**  
     * Send message to server.  
     * @param msg message that will be sent.  
     */  
    void sendToServer(final String msg) {   
        if (connected) {   
            try {   
                logMsg(msg);   
                os.write((msg).getBytes());   
                os.write("\r\n".getBytes());   
                os.flush();   
            } catch (IOException e) {   
                logMsg("Stream write error.", e);   
            }   
        } else {   
            wincall("warn_notconnected", null);   
        }   
    }   
  
    /**  
     * Close connection.  
     */  
    void closeConnect() {   
        if(reviever != null)   
            reviever.stop();   
           
        connected = false;   
        if (sock != null) {   
            try {   
                sock.close();   
            } catch (IOException e) {   
                e.printStackTrace();   
            }   
            sock = null;   
        }   
    }   
  
    /**  
     * Call function of outside explorer's script.  
     * @param function function name.  
     * @param param Parameter values.  
     */  
    protected void wincall(final String function, final Object[] param) {   
        Object[] realParam = param == null?new Object[0]:param;   
        try {   
            getWin().call(function, realParam);   
        } catch (JSException e) {   
            callAlert(   
                    "function : "  
                    + function   
                    + "(arg*"  
                    + realParam.length   
                    + ") is exist?");   
        }   
    }   
  
    /**  
     * Call alert function of outside explorer's script.  
     * @param msg Message.  
     */  
    protected void callAlert(final String msg) {   
        try {   
            getWin().call("alert", new String[] { msg });   
        } catch (JSException e1) {   
            e1.printStackTrace();   
        }   
    }   
  
    /**  
     * Log message when debug is true.  
     * @param msg Message.  
     */  
    protected void logMsg(final String msg) {   
        System.out.println(msg);   
    }   
  
    /**  
     * Log message when debug is true.  
     * @param msg Message.  
     * @param e Exception.  
     */  
    protected void logMsg(final String msg, final Throwable e) {   
        System.out.println(msg + "\r\nCause : " + e.getMessage());   
        e.printStackTrace();   
    }   
  
    /**  
     * Connect to server.  
     */  
    public void connect() {   
        if (connected) {   
            return;   
        }   
        logMsg("Connect to server...");    
  
        try {   
            // Conect to server..   
            sock = new Socket(host, port);   
            is = sock.getInputStream();   
            os = sock.getOutputStream();   
  
            connected = true;   
               
            // Thread that receive messages.   
            reviever = new Thread() {   
                public void run() {   
                    try {   
                        while (sock != null && !sock.isClosed()) {   
                            if (is.available() != 0) {   
                                byte[] buf = new byte[is.available()];    
                                is.read(buf);    
  
                                String line = new String(buf).trim();   
                                processMessage(line);   
                            }   
                        }   
                    } catch (IOException e) {   
                        logMsg("Error..", e);   
                    } finally {   
                        if (connected) {   
                            closeConnect();   
                            wincall("warn_connect_failed", null);   
                        }   
                    }   
                }   
            };   
            reviever.setDaemon(true);   
            reviever.start();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    }   
  
    public void sendMsg(final String toId, final String msg) {   
        try {   
            // TODO   
            sendToServer(msg);   
        } catch (Exception e1) {   
            logMsg("Error in sendMsg", e1);   
        }   
    }   
  
    public void quit() {   
        try {   
            sendToServer("quit");   
            closeConnect();   
            wincall("applet_quit", null);   
        } catch (Exception e) {   
            logMsg("Error in quit", e);   
        }   
    }   
  
    public boolean isConnected() {   
        return connected;   
    }   
  
}  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics