在Thunderbird扩展中,我使用以下代码等待传入的TCP连接:
hello()
{
echo "line 1"
echo "line 2"
echo "line 3"
echo "line 4"
insert new line of text "good bye" here
}
根据文档function MyExtension_OnNewConnection(srvSock, newSock)
{
var block = Components.interfaces.nsITransport.OPEN_BLOCKING |
Components.interfaces.nsITransport.OPEN_UNBUFFERED;
var istream = newSock.openInputStream(block, 0, 0);
var ostream = newSock.openOutputStream(block, 0, 0);
var cstream = Components.
classes["@mozilla.org/scriptableinputstream;1"].
createInstance(Components.interfaces.nsIScriptableInputStream);
cstream.init(istream);
var y = cstream.read(1);
cstream.close();
if(y == "")
{
var y = "The socket is Tx-Only!\r\n";
ostream.write(y, y.length);
}
istream.close();
ostream.close();
}
...
waitSocket = Components.classes["@mozilla.org/network/server-socket;1"].
createInstance(Components.interfaces.nsIServerSocket);
waitSocket.init(-1, false, -1);
waitSocket.asyncListen({
onSocketAccepted: MyExtension_OnNewConnection,
onStopListening: function(socket, status) {}
});
,只能在TCP套接字关闭时返回空字符串。
cstream.read()
函数将发送一些数据,这些数据仅在TCP套接字未关闭时才可用。
但是ostream.write()
返回一个空字符串,cstream.read()
发送一些数据,TCP连接的另一端接收字符串!
这意味着TCP连接单向(从头开始!)。
问题:
我已经尝试过:
ostream.write()
也不使用OPEN_BLOCKING
flags =>没效果。OPEN_UNBUFFERED
,而不是使用istream.available()
=>即使数据已由TCP连接的另一端发送,也将始终返回0。答案 0 :(得分:0)
我分析了Thunderbird的源代码:
显然openInputStream
使用了一个非常简单的"如果设置了OPEN_UNBUFFERED
且未设置OPEN_BLOCKING
,而其他三种组合使用了相当复杂的实现,则实现。
简单的实现非常有效,但是无法阻止套接字访问。
另一页说Javascript函数应该以非阻塞方式编写,所以我决定使用以下实现:
function CalledOnTimer()
{
try
{
while(true)
{
data = cstream.read(NumberOfBytes);
if(data == "")
{
/* Socket has been closed */
cstream.close();
istream.close();
ostream.close();
...
return;
}
/* Process the data */
...
}
}
catch(dummy)
{
/* Currently no (more) data on the socket */
restartTheTimer();
}
}
...
var istream = newSock.openInputStream(
Components.interfaces.nsITransport.OPEN_UNBUFFERED, 0, 0);
...
cstream.init(istream);
...
startTheTimer();