2012-04-16 3 views
4

파이어 폭스 확장 프로그램에서 원격 서버 (포트 9442에서 수신 대기)에 연결해야합니다. nsISocketTransportService을 사용하고 있는데 내 문제는 dataAvailable 이벤트를 수신하는 방법입니까? mozilla 문서를 검색하지만 유용한 것을 찾을 수 있습니다. 내 질문은 내가 어떻게 nsISocketTransportService.createTransport()을 사용하여 원격 서버에 연결할 때 데이터를들을 수 있습니까? 원격 TCP 서버에 연결하는 다른 방법이 있습니까?firefox 확장 기능에서 nsISocketTransportService를 사용하여 원격 서버에 연결하는 방법은 무엇입니까?

Components.utils.import("resource://gre/modules/NetUtil.jsm"); 

NetUtil.asyncFetch(poolRawInputStream, function(stream, result) 
{ 
    if (!Components.isSuccessCode(result)) 
    { 
    // Error handling here 
    } 

    var data = NetUtil.readInputStreamToString(stream, inputStream.available()); 
    ... 
}); 

이 방법의 단점 : 스트림이 닫힐 때까지 NetUtil 먼저 메모리에 모든 데이터를 읽어, 콜백이 호출되지 않습니다

var socket = Components.classes["@mozilla.org/network/socket-transport-service;1"] 
          .getService(Components.interfaces.nsISocketTransportService) 
          .createTransport(null, 0, host, port, null); 

var poolOutputStream = socket.openOutputStream(0, 0, 0); 

var helloMessage = JSON.stringify({type: 'hello', clientID: currentClientID}); 
    poolOutputStream.write(helloMessage, helloMessage.length); 

var poolRawInputStream = socket.openInputStream(0, 0, 0); 
var poolInputStream = Components.classes ["@mozilla.org/scriptableinputstream;1"] 
         .createInstance(Components.interfaces.nsIScriptableInputStream) 
         .init(poolRawInputStream); 

답변

2

당신은 NetUtil module가 사용할 수 있습니다. 당신이 직접 nsIInputStreamPump를 사용해야 할 것입니다 온다 당신이 데이터를 얻고 싶다면 :

Components.utils.import("resource://gre/modules/NetUtil.jsm"); 

var pump = Components.classes["@mozilla.org/network/input-stream-pump;1"] 
        .createInstance(Components.interfaces.nsIInputStreamPump); 
pump.init(poolRawInputStream, -1, -1, 0, 0, true); 

var listener = { 
    onStartRequest: function(request, context) {}, 
    onDataAvailable: function(request, context, stream, offset, count) 
    { 
    var data = NetUtil.readInputStreamToString(stream, count); 
    ... 
    }, 
    onStopRequest: function(request, context, result) 
    { 
    if (!Components.isSuccessCode(result)) 
    { 
     // Error handling here 
    } 
    } 
}; 

pump.asyncRead(listener, null); 
+0

을'nsIInputStreamPump' 내가 가능한 한 빨리 코드를 테스트하고 다시 결과가있을 것입니다 필요 정확히이다. 감사합니다 블라디미르 –

관련 문제