我正在尝试创建一个使用TcpSocket进行通信的Firefox插件。我已使用以下代码通过tcp成功发送了消息:
var tcpSocket = Cc["@mozilla.org/tcp-socket;1"].createInstance(Ci.nsIDOMTCPSocket);
var socket = tcpSocket.open("127.0.0.1", 3000);
socket.onopen = function() {
socket.send(sendText);
}
效果很好。
现在,我想收到tcp消息,而不是发送。我正在使用以下代码(基于MDN's TCP Socket article)
var tcpSocket = Cc["@mozilla.org/tcp-socket;1"].createInstance(Ci.nsIDOMTCPSocket);
var socket = tcpSocket.listen(3000);
socket.ondata = function (event) {
console.log(event);
};
但是它会记录以下错误(在运行cfx run
的cmd中):
console.error: my-addon:
Object
- message = Cannot modify properties of a WrappedNative
- fileName = undefined
- lineNumber = 6
...
而且,我可以说端口至少是活动的,因为如果我忽略错误并尝试向该端口发送tcp消息,则控制台会记录以下内容:
Received unexpected connection!
我在这里遗漏了什么吗?提前谢谢。
答案 0 :(得分:5)
我终于让它采用了不同的方法:
var port = 3000; //whatever is your port
const {Cc, Ci} = require("chrome");
var serverSocket = Cc["@mozilla.org/network/server-socket;1"].createInstance(Ci.nsIServerSocket);
serverSocket.init(port, true, -1);
var listener = {
onSocketAccepted: function(socket, transport) {
var input = transport.openInputStream(Ci.nsITransport.OPEN_BLOCKING,0,0);
var output = transport.openOutputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0);
var tm = Cc["@mozilla.org/thread-manager;1"].getService();
input.asyncWait({
onInputStreamReady: function(inp) {
try
{
var sin = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
sin.init(inp);
sin.available();
//Get request message
var request = '';
while (sin.available()) { request = request + sin.read(5120); }
var reqObj = { type: null, info: [] };
if(request != null && request.trim() != "") {
//Here is the message text
console.log(request);
}
}
catch(ex) { }
finally
{
sin.close();
input.close();
output.close();
}
}
}, 0, 0, tm.mainThread);
},
onStopListening: function(socket, status) {
}
};
serverSocket.asyncListen(listener);