如何创建源是接收数据包的输入流(ByteArrayInputStream和DataInputStream)?

时间:2018-04-29 23:41:27

标签: java sockets multicast datagram

这是我的代码的一部分(图像的多播订阅者)

public void subscribe() throws IOException {
    byte[] b = new byte[100];
    DatagramPacket datagram = new DatagramPacket(b, b.length, groupAddress, localPort);
    MulticastSocket socket = new MulticastSocket(localPort);
    socket.joinGroup(groupAddress);
    socket.send(datagram);

    while(true) {
      socket.receive(datagram); 
      System.err.println("Received " + datagram.getLength() +
        " bytes from " + datagram.getAddress());
      datagram.setLength(b.length); 
      socket.leaveGroup(groupAddress);
      socket.close();
    }

这是任务:

创建一个输入流,其源是收到的数据包(例如ByteArrayInputStreamDataInputStream)。

这是发布者:

private void castOneImage(DatagramSocket socket,String imageFn,SocketAddress groupSocketAddress){

    byte[] imageBytes = null;
    try (InputStream in = getClass().getClassLoader().getResourceAsStream(imageFn);
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream()) {
        if (in == null) {
            throw new FileNotFoundException("Cannot open image file " + imageFn);
        }
        int b;
        while ((b = in.read()) != -1) {
            byteOut.write(b);
        }
        imageBytes = byteOut.toByteArray();

        byteOut.reset();
        ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.SIZE / 8);
        byteBuffer.putInt(imageBytes.length);
        byteOut.write(byteBuffer.array());
        byteOut.write(imageBytes);
        imageBytes = byteOut.toByteArray();

        DatagramPacket packet = new DatagramPacket(imageBytes, imageBytes.length, groupSocketAddress);
        socket.send(packet);
    } catch (IOException e) {
        // if there is an error for this image, we soldier on hoping other images may be good
        LOGGER.warn("I/O error: " + e.getMessage(), e);
    }
}

1 个答案:

答案 0 :(得分:0)

使用ByteArrayInputStream

DataInputStream dis = new DataInputStream(new ByteArrayInputStream(datagram.getData(), datagram.getOffset(), datagram.getLength()));

close()移出循环。如果您要关闭套接字,则不必明确离开该组。

编辑要重新构建图像数据:

int length = dis.readInt();
byte[] image = new byte[length];
dis.readFully(image);

但当然,由于数据报知道自己的长度,你根本不需要发送或接收length字。