我使用Anko在后台进行以下udp联网:
虽然到目前为止一切正常,但是doAsync
正文在15秒后就不再被调用。
我的功能如下:
// handler function, that calls sendRquest every 5 seconds
val handler = Handler()
val runnable = object : Runnable {
override fun run() {
sendRequest(message)
handler.postDelayed(this, 5000)
}
}
handler.postDelayed(runnable, 500)
// function that is called every 5 sec
private fun sendRequest(message: String) {
val ip = getGlobalIP()
doAsync {
var run = true
//some udp stuff
}
}
当我调试时,可以看到val ip =
行被调用,而var run =
行在这15秒之后没有被调用。
我等待了大约一分钟,但doAsync
正文不再被调用。
有人知道为什么吗?
*编辑:*
这是完整的doAsync
正文:
private fun sendRequest(relay: Relay, message: String, callback: (String, Relay) -> Unit) {
val test = 0
doAsync {
var run = true
val ipAddress = InetAddress.getByName(relay.ip)
try {
val packet = DatagramPacket(message.toByteArray(), message.length, ipAddress, relay.port!!)
val udpSocket = relay.socket!!
udpSocket.send(packet)
while (run) {
try {
val newMessage = ByteArray(8000)
val newPacket = DatagramPacket(newMessage, newMessage.size)
Log.i("UDP client: ", "about to wait to receive")
udpSocket.receive(newPacket)
val response = String(newMessage, 0, newPacket.length)
Log.d("Received text", response)
uiThread {
callback(response, relay)
}
} catch (e: IOException) {
Log.e("UDP client error", "error: ", e)
toast(e.message!!)
uiThread {
run = false
}
throw IOException(e)
}
}
} catch (e: IOException) {
e.printStackTrace()
toast(e.message!!)
}
}
}
答案 0 :(得分:0)
anko的doAsync
在内部SchedulerService
上运行。
主要问题是您的doAsync
调用是否结束,因为在某个时刻它可能同时运行了足够多的调用,因此android决定不再调度更多线程,直到一些较旧的线程结束为止。
如果没有看到doAsync
通话的全部内容,就无法给出更具体的答案。
答案 1 :(得分:0)
具有将套接字存储在异步块外部的字段。
运行异步操作一次启动套接字,然后可以使用from flask import Flask, request, Response, jsonify
import webbrowser
import os
import time
import json
import requests
...
some functions here
...
app = Flask(__name__)
@app.route('/tests', methods=['POST'])
def test():
if "text" in request.form:
if not request.form["text"]:
return slackCommandResponse("No parameters provided. Please run /run-tests <url> <test_ID>")
else:
params = request.form["text"]
user_id = request.form["user_id"]
payload = {'token': ''+token+'', 'user': user_id }
user_req = requests.get('https://slack.com/api/users.info', params=payload)
user_data = user_req.json()
real_name = user_data['user']['real_name']
user_email = user_data['user']['profile']['email']
if len(params.split()) > 2:
return slackCommandResponse("More parameters are provided than needed. Please run /run-tests <url> <test_ID>")
else:
baseUrl = params.split(" ")[0]
if not len(params.split()) > 1:
# here is the response need to be send
return slackCommandResponse("No test ID provided. Running all tests. You will be notified upon progress.")
# code part starting from here need to be executed after response above
for file in files(path):
file_full_path = os.path.join(path, file)
ID = file[:-4]
url=baseUrl+"&respondentid="+ID
apiUrl=apibase+"&respondentid="+ID
test_answer = 5
webbrowser.get(chrome_path).open(url)
openFile(file_full_path)
time.sleep(5)
checkAppIsRunning("AmcEngine.exe")
responseContent = requests.get(apiUrl)
respjson = responseContent.json()
test_result = (respjson["questions"][0]["qResponseData"]["basketContent"][0]["quantity"])
if test_result == test_answer:
slackResponse("Test "+ID+" passed")
else:
slackResponse("Test "+ID+" failed")
else:
return slackCommandResponse("Cannot run single test yet")
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
通过套接字发送数据包(它是非阻塞的)。
否则,您可以在收到一个响应(如果确定足够)以释放线程后杀死套接字。