【问题标题】:How to create an input stream whose source is the received packet (ByteArrayInputStream and DataInputStream)?如何创建一个输入流,其源是接收到的数据包(ByteArrayInputStream 和 DataInputStream)?
【发布时间】:2018-04-29 23:41:27
【问题描述】:

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

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

【问题讨论】:

    标签: java sockets multicast datagram


    【解决方案1】:

    使用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 字。

    【讨论】:

    • 如何使用这个“dis”来检索从它发送来的图像?
    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2014-05-08
    • 2015-02-27
    • 2018-02-27
    • 1970-01-01
    相关资源
    最近更新 更多