1

我正在通过从 FF 附加组件到 Java 服务器的套接字写入。我写了几个请求,但服务器只得到第一个。我不知道发生了什么。

这是我的代码:

const {Cc,Ci, Cu} = require("chrome");

var toSend = ["hi1\n", "hi2\n"];

var {NetUtil} = Cu.import("resource://gre/modules/NetUtil.jsm");

function sendNextString(outstream) {
  if (!toSend.length)
    return;  // Nothing left to send

  var outputData = toSend.shift();
  console.log(outputData);

  var instream = Cc["@mozilla.org/io/string-input-stream;1"]
        .createInstance(Ci.nsIStringInputStream);

  instream.setData(outputData, outputData.length);

  NetUtil.asyncCopy(instream, outstream, function(aResult) {  
    if (!Components.isSuccessCode(aResult))
        console.log("ERROR: writing to socket")
    });
}


exports.main = function() {
    try  {
        // At first, we need a nsISocketTransportService
        var transportService =  
            Cc["@mozilla.org/network/socket-transport-service;1"]
            .getService(Ci.nsISocketTransportService);  

        // Try to connect to localhost:2222
        var transport = transportService.createTransport(null, 0, "localhost", 6666, null);  

        var stream = transport.openInputStream(Ci.nsITransport.OPEN_UNBUFFERED,null,null); 
        var instream = Cc["@mozilla.org/scriptableinputstream;1"]
            .createInstance(Ci.nsIScriptableInputStream); 

        // Initialize
        instream.init(stream);
        var outstream = transport.openOutputStream(0, 0, 0);

        var dataListener = { 
            onStartRequest: function(request, context){},

            onStopRequest: function(request, context, status){
                instream.close();
                outstream.close();
            }, 

            onDataAvailable: function(request, context, inputStream, offset, count) { 
                var data = instream.read(count); 
                console.log(data);

                // Write data
                sendNextString(outstream);        
            }, 
        };

        var pump = Cc["@mozilla.org/network/input-stream-pump;1"]
                .createInstance(Ci.nsIInputStreamPump); 
        pump.init(stream, -1, -1, 0, 0, false); 
        pump.asyncRead(dataListener, null); 

        // Write data
        sendNextString(outstream);

    } catch (e){ 
        console.log("Error" + e.result + ": " + e.message); 
        return e; 
    } return null;
};

所以,当我运行它时,我得到:

Client > hi1
Server > bye1
Client > hi2

它应该是:

Client > hi1
Server > bye1
Client > hi2
Server > bye2

编辑:在 asyncCopy 调用中添加了一个回调来检查错误,但它可以正常工作。

Edit2:调试服务器中用于读取附加请求的循环在第二次从输入流中读取时被阻塞。

while ((inputLine = in.readLine()) != null) {
  if (inputLine.equals("-1")) break;
  System.out.println("Client < " + inputLine);
  outputLine = process(inputLine);
  out.println(outputLine);
  System.out.println("Server > " + outputLine);
}
4

0 回答 0