Android 3.0 套接字响应延迟
我已经开始了一个利用套接字编程的 Android 项目。平台是Android 3.0。由于平台要求,我在 AsyncTask 中应用套接字操作。
我连接到服务器,成功发送命令,但问题是我收到的响应不完整。发送命令后,我必须等待一段时间才能完全响应,否则只是部分响应。我发现等待时得到完整响应的方式是在调试模式期间,我等了一会儿才继续使用响应变量的下一行代码,并得到了完整的预期结果。
我尝试设置一个计时器
Timer myTimer = new Timer();
myTimer.wait(2000);
,但这使得整个响应根本不起作用。任何建议将不胜感激。
I have started an Android project utilizing socket programming. Platform is Android 3.0. Due to platform requirements I am applying the socket operations in AsyncTask.
I connect to the server, send commands successfully but the problem is that the responses I receive come incomplete. After sending a command, I have to wait for sometime for the response to come completely, otherwise it is just partial response. The way I found out I get the full response when I wait is during debug mode, I waited a while before going on to the next line of code which I utilize the response variable and I got the full expected result.
I tried putting a timer
Timer myTimer = new Timer();
myTimer.wait(2000);
but that just made the whole response not work at all. Any suggestions would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,你不应该遇到这个问题。您的网络连接可能有问题,因为这种延迟对于任何平台来说都是不正常的。但如果您确实想以编程方式解决这个问题,请继续阅读。
您不想为此使用计时器,因为:
a)即使在等待之后,您也无法确定是否已获得该值,
b)如果您确实很快获得了该值,您将不必要地减慢速度。
更好的选择是使用一些代码来检查循环中接收到的值以查看其是否完整,一旦完成,则继续进行下一位。
First of all, you shouldn't be having this problem. There is probably something wrong with your network connection, because that amount of latency is not normal for any platform. But if you do want to tackle it programmatically, read on.
You don't want to use a timer for that, because:
a) even after waiting you can't be certain you've got the value, and
b) you will be slowing things down unnecessarily if you do get the value quickly.
The better option is to have some code that checks the received value in a loop to see if it's complete, and once it is, move on to the next bit.