java 从套接字读取所有数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17614431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read all data from socket
提问by Tala
I want read all data ,synchronously , receive from client or server without readline()
method in java(like readall()
in c++).
I don't want use something like code below:
我想同步读取所有数据,从客户端或服务器接收没有readline()
java 中的方法(如readall()
在 c++ 中)。
我不想使用类似下面的代码:
BufferedReader reader = new BufferedReader(new inputStreamReader(socket.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
document.append(line + "\n");
What method should i use?
我应该使用什么方法?
回答by Tala
If you know the size of incoming data you could use a method like :
如果您知道传入数据的大小,则可以使用以下方法:
public int read(char cbuf[], int off, int len) throws IOException;
where cbuf is Destination buffer.
其中 cbuf 是目标缓冲区。
Otherwise, you'll have to read lines or read bytes. Streams aren't aware of the size of incoming data. The can only sequentially read until end is reached (read method returns -1)
否则,您将不得不读取行或读取字节。流不知道传入数据的大小。只能顺序读取直到到达结束(读取方法返回 -1)
refer here streams doc
在这里参考流文档
sth like that:
诸如此类:
public static String readAll(Socket socket) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
sb.append(line).append("\n");
return sb.toString();
}
回答by BQuadra
You could use something like this:
你可以使用这样的东西:
public static String readToEnd(InputStream in) throws IOException {
byte[] b = new byte[1024];
int n;
StringBuilder sb = new StringBuilder();
while ((n = in.read(b)) >= 0) {
sb.append(b);
}
return sb.toString();
}