2

我需要将来自套接字的传入数据获取到 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);
}
4

3 回答 3

4

此代码将读取所有字节并将它们存储在 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();
}
于 2012-09-18T16:34:25.700 回答
2

int count = SocketChannel.read(ByteBuffer).如果您不使用,不确定为什么要添加“socketchannel”标签SocketChannels,但这是如何做到的。

于 2012-09-18T23:59:48.673 回答
-1
        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();
        }
于 2012-09-18T16:49:33.673 回答