如何读取插座连接数据 - 机器人 [英] How to read data from socket connection - android

查看:133
本文介绍了如何读取插座连接数据 - 机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有TCP客户端应用程序,它成功地协商连接到服务器并接收缓冲输出,但我需要知道的是如何在无需等待缓冲填写或服务器终止连接读取服务器的响应。结果
在这个循环

I've got TCP client app which successfully negotiates connection to server and receives buffered output, but what I need to know is how to read server responses without waiting to buffer to fill out or server to end connection.
In this loop:

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
   ...some code here...         
}

我的应用程序只是冻结。结果
如何读取一行或者一空,如果缓冲区为空,继续执行一个程序?结果
是否有可能超时此读书,给一些时间来应对服务器?

mine app just freezes.
How to read just one line or empty string if buffer is empty and continuing to execute a program?
Is it possible to timeout this reading, to give server some time to respond?

推荐答案

底层协议应该提供某种形式的同步,例如HTTP的的Content-Length \\ n \\ r

The underlying protocol should provide some kind of synchronisation, like HTTP's Content-Length or \n\r.

否则,你会被堵塞,即使你的程序以字节读取的字节。

Otherwise, you'll get blocked even if your program reads byte by byte.

或者你可以使用非阻塞套接字

这篇关于如何读取插座连接数据 - 机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆