3

我有一个用java编写的服务器监听本地主机中的一个端口。我正在尝试通过 Firefox 扩展连接到它。我可以发送请求并接收响应,但只能发送一次。然后,我不知道它为什么停止工作:我什至无法发送响应。

我认为流在某个时候会关闭,但我不知道为什么,因为我将pump界面中的参数设置为在完成后不关闭流...

这是我的代码:

const {components} = require("chrome");
const {NetUtil} = components.utils.import("resource://gre/modules/NetUtil.jsm");


var transport = null;
var outstream = null, instream = null;
var instream = components.classes["@mozilla.org/scriptableinputstream;1"]
        .createInstance(components.interfaces.nsIScriptableInputStream);
var pump = components.classes["@mozilla.org/network/input-stream-pump;1"]
        .createInstance(components.interfaces.nsIInputStreamPump);
var dataListener = null;

exports.connect = function(server, port, callback) {
    transport = components.classes["@mozilla.org/network/socket-transport-service;1"]
                          .getService(components.interfaces.nsISocketTransportService)
                      .createTransport(["udp"], 0, server, port, null);                          
    outstream = transport.openOutputStream(0, 0, 0);
    stream = transport.openInputStream(0, 0, 0);

    // Initialize
    instream.init(stream);
    pump.init(stream, -1, -1, 0, 0, false);

    dataListener = {
        receivedData: [],

        onStartRequest: function(request, context) {
            console.log("Connected to server");
        },

        onStopRequest: function(request, context, status) {
            console.log("End of request");                     
        }, 

        onDataAvailable: function(request, context, inputStream, offset, count) {
            var data = instream.read(count).replace(/\n/gm,'');         
            callback(data);   
        }
    };
    pump.asyncRead(dataListener, null); 
}

exports.send = function(data) {
    // Send data
    var outData = data + '\n';
    outstream.write(outData, outData.length);
}

exports.close = function(data) {
    // Close stream
    outstream.close();
    stream.close();
}

编辑:java服务器的代码

    public PluginConnection(int newPort) throws IOException {
    serverSocket = new ServerSocket(this.port);
}

public void send(String message) {
    if (this.clientSocket != null) {
        out.println(message);
    } else {
        System.err.println("ERROR: message could not be sent because "
                + "connection is not established.");
    }
}


public void open() {        
    try {
        clientSocket = serverSocket.accept();           
    } catch (IOException e) {
        System.err.println("ERROR: PIRServer could not open connection.");
        e.printStackTrace();
    }       
}

public String getRequest() {
    try {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out = new PrintWriter(clientSocket.getOutputStream(), true);
    } catch (IOException e) {
        System.err.println("ERROR: PIRServer could not open streams.");
        e.printStackTrace();
    }

    String query = null;
    try {
        query = in.readLine();
    } catch (IOException e) {
        System.err.println("ERROR: could not open parse query.");
        e.printStackTrace();
        out.println("-1");
    }
    return query;
}

public void close() {
    try {
        if (in != null) {
            in.close();             
        }           
        if (out != null) {
            out.close();                
        }           
        if (clientSocket != null) {
            clientSocket.close();
        }
        if (serverSocket != null) {
            serverSocket.close();
        }
    } catch (IOException e) {
    } catch (Exception e) { 
        e.printStackTrace();
        System.exit(-1);
    }
}

有谁知道解决方案?

4

1 回答 1

0

这可能不是您正在寻找的答案,但我想我还是建议您这样做。

您可以考虑将 node.js 作为 Web 套接字服务器并在 Firefox 中使用 MozWebSocket,而不是使用 Java。它真的很好用。例如,在 Firefox 插件中:

if (typeof (MozWebSocket) != 'undefined') {
   mysocket = new MozWebSocket(SOCKET_URL);
} else if (typeof (WebSocket) != 'undefined') {
   mysocket = new WebSocket(SOCKET_URL);
} else {
   alert("Can't get socket");
}
if (mysocket === null) {
   alert("Can't get socket");
}

mysocket.onerror = function(event) {
/* error handling here */
};

mysocket.onopen = function() {
   mysocket.send(JSON.stringify(msg));
   mysocket.close();
}

在服务器端,这就是 node.js 的全部内容:

var wss, http, server, wsServer, Client, fs, qs;

wss = require('node_modules/websocket/lib/WebSocketServer');
http = require('http');
fs = require('fs');
qs = require('querystring');

initializeServer();

wsServer.on('connect', function(connection) {
    console.log((new Date()) + " Connection accepted.");
    connection.on('message', function(message) {
        if (message && message.type === 'utf8') {
            var data = JSON.parse(message.utf8Data);
            /* parse data here */
        }
        else {
            console.log("Data is not utf8! Data = " + message);
        }
    });

    connection.on('close', function(connection) {
    console.log((new Date()) + " Client " + connection.remoteAddress + " disconnected.");
    });
});

function initializeServer() {
    server = http.createServer(function(request, response) {
    });
    server.listen(6969, function() {
        console.log((new Date()) + " Server is listening on port 6969");
    });

    wsServer = new wss({
        httpServer: server,
     maxReceivedMessageSize: 0x800000,
        autoAcceptConnections: true
    });
}
于 2013-03-12T07:27:13.837 回答