[英]Java reading from socket
In a loop, this code runs (server side): 在一个循环中,此代码运行(服务器端):
try {
BufferedInputStream is = new BufferedInputStream(cnn.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
int character;
StringBuffer process = new StringBuffer();
while ( (character = isr.read()) != 13) {
process.append( (char) character);
}
println("Input: " + process.toString());
} catch (Exception e) { }
the client is not sending anything, but process.toString()
outputs infinite question marks. 客户端没有发送任何内容,但是
process.toString()
输出无限的问号。 the variable is
outputs this: java.io.InputStreamReader@510ebe18
(the last number always changes) 变量
is
输出以下内容: java.io.InputStreamReader@510ebe18
(最后一个数字始终会更改)
Isn't the input supposed to be empty and fall back to catch
block if the client doesn't send anything? 如果客户端不发送任何内容,输入是否不应该为空并回退以
catch
块?
What am i doing wrong? 我究竟做错了什么?
note: the while-loop goes on forever because there is no end to the input, i was able to see the question marks comming out by putting a limit of 100 characters to the process
variable. 注意:while循环永远持续下去,因为输入没有尽头,我可以通过在
process
变量中限制100个字符来看到问号。
?
marks are probably because the stream source is returning -1 to indicate the end of the stream. 标记可能是因为流源返回-1来指示流的结束。 But the while loop is waiting for a carriage return.
但是while循环正在等待回车。
The read
call is blocking and will wait for the input. read
调用处于阻塞状态,将等待输入。 Only if it detects the end of the stream or on some erroneous condition does it throw an exception. 仅当它检测到流的末尾或处于某种错误条件时,它才会引发异常。
I presume you are reading lines. 我想你正在看台词。 It would be efficient to use
BufferedReader
instead of reading it byte by byte. 使用
BufferedReader
而不是逐字节读取它会很有效。
So, if you were reading from standard input. 因此,如果您正在从标准输入中读取。 You could do something like :
您可以执行以下操作:
BufferedReader reader = new BufferedReader(
new InputStreamReader(new BufferedInputStream(System.in)));
try {
StringBuilder result = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
result.append(line);
}
//process result
System.out.println(result);
} catch (IOException e){
e.printStackTrace();
}
The toString
method of InputStreamReader
is not overloaded. InputStreamReader
的toString
方法未重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.