我想读取和处理一行中包含单个或多个命令的String流。
我目前正在使用InputStream in = socket.getInputStream();
我的输入流。
同样用于处理输入的典型线程:
public void run() {
String input = "";
try {
int data = 0;
while (!isInterrupted()) {
while ((data = in.read()) != -1 && !isInterrupted()) {
input += Integer.toHexString(data);
handleInput(input);
}
try {
sleep(500);
} catch (InterruptedException e) {
break;
}
}
socket.close();
return;
} catch (IOException e) {
main.log("Connection lost...");
main.log(e.toString());
main.stopBTCommunication();
main.startBTServer();
}
}
handleInput()
设计用于处理赋予它的任何String并正确响应。此实现的问题是,handleInput()
从中读取的每个字节都会调用该实现in.read()
。我知道,我可以使用BufferedReader.readLine()
,但这将要求每个传入的命令都"\n"
附加到该命令上,这不是事实,不能更改。
我知道
while (!isInterrupted()) {
while ((data = in.read()) != -1 && !isInterrupted()) {
有点麻烦,但是基本上它希望Thread读取,直到没有新内容被读取为止,然后处理该输入,然后再次读取...
编辑:
因此,基本上,我需要的是非阻塞性的read()
。
编辑2:
传入命令和命令链的外观如何:
因此,命令链可能看起来像以下之一:
"s"
"srlff"
= "s" + "rlff"
"rlffwlbb2e2e2e2erlbb"
= "s" + "rlff" + "wlbb2e2e2e2e" + "rlbb"
您可以像这样读取字节数组
int bytesRead = 0;
byte[] buffer = new byte[1024]; // reads up to 1024 byte chunks
while((bytesRead = in.read(buffer)) != -1) {
for ( int i = 0; i < bytesRead; i++ ) {
input += Integer.toHexString(buffer[i]);
}
handleInput(input);
}
上面的代码调用与您的旧代码相同,“输入”一直在增长,并一遍又一遍地用于调用handleInput()。不确定这是否是您的意图,但看起来可疑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句