目前我正在开发一个可在tizen设备上运行的webapp(Samsung Gear S3)。该应用程序的目的是在刷卡时向websocketserver发送消息(用Python编写并在我的计算机上运行)。当我向右滑动时,我发送一个string1,当我向左滑动时,我发送string2。 问题是消息到达服务器需要一段时间(大约5秒)。这种延迟只发生在我运行一段时间后第一次发送消息时。据我所知,它的10秒钟。这意味着我可以在最后一个10秒内发送任何消息immidiataly。但是当我暂停超过10秒时,会有5秒的延迟。
所以qustion是什么导致延迟的原因?或者我该如何避免这种情况。好像有一个超时,但我怎么能避免这个呢?
客户端(Tizen SmartWatch)上的代码是用Javascript和jquery编写的。
这是客户端代码我做了一点简短。 HTML部分不包括在内。
<script>
var webSocketURL1 = "ws://";
var webSocketURL2 = "Computer10";
var webSocketURL3 = ":9998/echo";
function WS(String){
var webSocketURL=webSocketURL1+webSocketURL2+webSocketURL3;
var webSocket = new WebSocket(webSocketURL);
webSocket.onopen = function (e) {
console.log('connection open, readyState : ' + e.target.readyState);
webSocket.send(String);
};
function closeConnection() {
if (webSocket.readyState === 1) {
webSocket.close();
}
};
}
</script>
<script>
$(document).ready(function(){
$("body").on("swiperight",function(){
WS("string1");
});
});
</script>
<script>
$(document).ready(function(){
$("body").on("swipeleft",function(){
WS("string2");
});
});
</script>
答案 0 :(得分:2)
我建议保留var&#39; webSocket&#39;全局声明,而不是在函数范围内。
再次检查你的python代码,你是否正在关闭任何不必要/可选的套接字?试着摆脱它们。
答案 1 :(得分:1)
这里我改变了部分代码。请测试一下,如果发现任何问题,请告诉我
<script>
var webSocketURL = 'ws://Computer10:9998/echo';
var ws;
function connect() {
//alert('connect');
ws = new WebSocket(webSocketURL, []);
// Set the function to be called when a message is received.
ws.onmessage = handleMessageReceived;
// Set the function to be called when we have connected to the server.
ws.onopen = handleConnected;
// Set the function to be called when an error occurs.
ws.onerror = handleError;
}
function handleMessageReceived(data) {
// Simply call logMessage(), passing the received data.
logMessage(data.data);
}
function handleConnected(data) {
// Create a log message which explains what has happened and includes
// the url we have connected too.
var logMsg = 'Connected to server: ' + data.target.url;
// Add the message to the log.
logMessage(logMsg)
}
function handleError(err) {
// Print the error to the console so we can debug it.
console.log("Error: ", err);
}
function logMessage(msg) {
// $apply() ensures that the elements on the page are updated
// with the new message.
$scope.$apply(function() {
//Append out new message to our message log. The \n means new line.
$scope.messageLog = $scope.messageLog + msg + "\n";
});
}
$(document).ready(function(){
$("body").on("swiperight",function(){
ws.send("string1");
});
});
$(document).ready(function(){
$("body").on("swipeleft",function(){
ws.send("string2");
});
});
connect();
</script>