java 如何从 TCP 套接字获取数据到 ByteBuffer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12478845/
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
How to get data from TCP socket into a ByteBuffer
提问by user1372020
I need to get incoming data from a socket into a ByteBuffer and I do not know how to do it. I am new to this field and therefore not sure of the best way to start. I found the following but that is not what I want as it gets the data in line but I need to have all of my data in bytebuffer for other purposes.
我需要将传入的数据从套接字获取到 ByteBuffer 中,但我不知道该怎么做。我是这个领域的新手,因此不确定最好的开始方式。我发现了以下内容,但这不是我想要的,因为它可以在线获取数据,但我需要将所有数据都放在字节缓冲区中以用于其他目的。
ServerSocket welcomeSocket = new ServerSocket(Integer.parseInt(ibmPort));
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
setRequestDataFromCT(clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
回答by pmoleri
This code will read all the bytes and store them in a ByteBuffer, you may have to adjust the bufferSize to store all the data you need.
此代码将读取所有字节并将它们存储在 ByteBuffer 中,您可能需要调整 bufferSize 以存储您需要的所有数据。
int bufferSize = 8192;
ServerSocket welcomeSocket = new ServerSocket(Integer.parseInt(ibmPort));
while (true) {
Socket connectionSocket = welcomeSocket.accept();
ByteBuffer bf = ByteBuffer.allocate(bufferSize);
BufferedInputStream inFromClient = new BufferedInputStream(connectionSocket.getInputStream());
while (true) {
int b = inFromClient.read();
if (b == -1) {
break;
}
bf.put( (byte) b);
}
connectionSocket.close();
}
回答by user207421
int count = SocketChannel.read(ByteBuffer).
Not sure why you added the 'socketchannel' tag if you weren't using SocketChannels
, but this is how to do it.
int count = SocketChannel.read(ByteBuffer).
如果您不使用SocketChannels
,不确定为什么要添加 'socketchannel' 标签,但这是如何做到的。
回答by user1372020
ServerSocket welcomeSocket = new ServerSocket(Integer.parseInt(ibmPort));
while (true) {
Socket connectionSocket = welcomeSocket.accept();
InputStream stream = connectionSocket.getInputStream();
byte[] data = new byte[1024];
int count = stream.read(data);
ByteBuffer bb = ByteBuffer.allocate(data.length);
bb.put(data);
bb.flip();
}