【问题标题】:How to set a timeout for Firefox OS TCP Sockets如何为 Firefox OS TCP 套接字设置超时
【发布时间】:2015-08-16 18:59:53
【问题描述】:
我正在开发一个firefox-os 应用程序,该应用程序尝试通过TCP Socket API 按顺序连接到 IP 列表。
但是,如果它在几秒钟内没有连接,并且连接不活动超过几秒钟,我想关闭套接字。
例子:
var socket = navigator.mozTCPSocket.open(IP, port);
//would like to set timeout for connection here
socket.onopen = function(event){
var serviceRequest = new Object();
serviceRequest.type = "myService";
var sendStr = JSON.stringify(serviceRequest);
sendStr+="\n";
sendStr = sendStr.toString('utf-8');
socket.send(sendStr);
//and would like a timeout for receiving data here
socket.ondata = function(event){
//etc
}
}
【问题讨论】:
标签:
firefox-os
javascript
sockets
firefox
tcp
firefox-os
【解决方案1】:
据我所知,没有办法指定超时。如果你想指定一个超时时间,你应该使用通常的 javascript setTimeout,存储它的 id。
使用 TCPSocket 对象上的onopen 事件取消超时。如果超时被触发。你可以在socket上调用close方法。
var socket = navigator.mozTCPSocket.open(IP, port);
var timeout = setTimeout(function () {
socket.close()
}, timeoutDuration)
//would like to set timeout for connection here
socket.onopen = function(event){
// Prevent from timingout if open
clearTimeout(timeout)
var serviceRequest = new Object();
serviceRequest.type = "myService";
var sendStr = JSON.stringify(serviceRequest);
sendStr+="\n";
sendStr = sendStr.toString('utf-8');
socket.send(sendStr);
//and would like a timeout for receiving data here
socket.ondata = function(event){
//etc
}
}