如何将数据从TCP套接字转换为ByteBuffer

时间:2012-09-18 14:17:25

标签: java sockets tcp bytebuffer socketchannel

我需要将来自套接字的传入数据传入ByteBuffer,我不知道该怎么做。我是这个领域的新手,因此不确定最好的开始方式。我找到了以下内容,但这不是我想要的,因为它获取了数据,但我需要将所有数据都放在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);
}

2 个答案:

答案 0 :(得分:3)

此代码将读取所有字节并将其存储在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();
}

答案 1 :(得分:-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();
        }