How to get data from TCP socket into a ByteBuffer

回眸只為那壹抹淺笑 提交于 2019-12-04 19:21:09

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

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.

        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();
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!