使用套接字进行数据传输。 Java& Firefox扩展

时间:2011-08-23 09:10:47

标签: java javascript sockets firefox-addon

我正在尝试在Java(客户端)中的程序和JavaScript(服务器)中的Firefox扩展之间实现数据传输。我不能只使用一个插座发送和接收。请帮我解决这个问题。现在,客户端从服务器获取一条消息,但是给它一条空白消息。

客户端(Java):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketOptions;

public class JustForTest {

    /**
     * @param args the command line 
     * 
     * Connect to FF Plugin (Server). Send URL and waiting for innerHTML
     */
    public static void main(String[] args) throws IOException {
        String messageFromServer;
        String messageToServer = "http://google.pl/";

        Socket clientSocket = new Socket("localhost", 8888);

        try {
            System.out.println("Socket is connected to 127.0.0.1:8888");
            // Send URL to Firefox Plugin
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            out.write(messageToServer);
            InputStream inStream = clientSocket.getInputStream();
            // Is waiting for answer from Firefox Plugin
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
            System.out.println(reader.readLine());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (clientSocket != null && clientSocket.isConnected()) {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.print(e);
                }
            }
        }
    }
}

Firefox扩展程序(JavaScript):

    var BeansServer = new function () {

    /*
     * Listen for connections. Transmit
     */
    var listener = {
        onSocketAccepted: function(serverSocket, transport) {
            addSpan("Accepted connection on " + transport.host + ":" + transport.port);
            var input = transport.openInputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0);//.QueryInterface(Ci.nsIAsyncInputStream);
            var output = transport.openOutputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0);
            var sin = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);

            try{
                sin.init(input);
                var readBytes = sin.available();

                var request = '';
                request = sin.read(readBytes);
                addSpan('Received: ' + request);

                getUrl(request);

                output.write("yes", "yes".length);
                output.flush();
            }
            finally{
                sin.close();
                input.close();
                output.close();
            }
        }
    }

    /*
     * Main
     */
    this.start = function() {
        var serverSocket = Cc["@mozilla.org/network/server-socket;1"].createInstance(Ci.nsIServerSocket);
        serverSocket.init(8888, true, 5);
        addSpan("Opened socket on " + serverSocket.port);
        serverSocket.asyncListen(listener);
    };

    /*
     * Opening the page in the browser. Checks the HTML status of the loaded page
     */
    function getUrl(url){
        var xmlhttp = getXmlHttp();
        xmlhttp.open('GET', 'http://google.pl', true);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                if(xmlhttp.status == 200) {
                    alert(xmlhttp.status);
                }
            }
        };
        xmlhttp.send(null);
    }

    function getXmlHttp(){
        var xmlhttp;
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
            xmlhttp = new XMLHttpRequest();
        }
        return xmlhttp;
    }

    function getBrowser(){
        if (!gBrowser)
            gBrowser = document.getElementById("content");
        return gBrowser;
    }

    /*
     * Displays a string on a page in the browser
     */
    function addSpan(content2) {
        var mySpan = content.document.createElement('span');
        mySpan.innerHTML = content2 + '<br/>';
        content.document.body.appendChild(mySpan);
    }
}

2 个答案:

答案 0 :(得分:0)

您的问题可能与您没有在客户端代码中刷新输出流有关:

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.write(messageToServer);

虽然使用autoflush = true创建PrintWriter,但只有在使用printlnprintfformat方法时,autoflush才会生效(按照javadocs),所以我将您的代码更改为:

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(messageToServer);

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.write(messageToServer);
out.flush();

编辑:

虽然我没有使用Firefox库的经验,但我也想知道读取输入的Javascript代码是否不完整,我想知道你是否可以尝试以下(它应该以512字节的块读取输入) :

var request = '';
while (sin.available()) {
    request = request + sin.read(512);
}

此外,在Java客户端中读取响应时,我会:

String line;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

答案 1 :(得分:0)

需要关闭Java中的out

out.close();