How to get data from TCP socket into a ByteBuffer

2020-07-24 05:33发布

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.

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);
}

3条回答
手持菜刀,她持情操
2楼-- · 2020-07-24 05:49

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.

查看更多
聊天终结者
3楼-- · 2020-07-24 05:57

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.

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();
}
查看更多
ゆ 、 Hurt°
4楼-- · 2020-07-24 05:59
        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();
        }
查看更多
登录 后发表回答