Java - 通过ObjectOutputStream发送ImageIcon是第一次,但不是之后

时间:2016-04-18 17:08:03

标签: java sockets objectinputstream objectoutputstream

我正在开发Java中的服务器/客户端项目,在程序运行期间的任何时候,客户端都可以请求一组与唯一ID相关的详细信息,并且服务器返回相关的一组详细信息。这是通过访问PrintWriter的{​​{1}}个对象完成的,并且运行正常。

我试图还包括从服务器向客户端发送/接收图像,并从程序中遇到一些非常奇怪的行为。

发送和接收图像的方法如下所示:

服务器端:

socket.getOutputStream

客户端:

//send image associated with item
//through ObjectOutputStream to client
private void sendItemImage(BidItem item)
{
    try
    {
        //wrap object output stream around
        //output stream to client at this socket
        ObjectOutputStream imageOutput =
                new ObjectOutputStream(client.getOutputStream());
        //send image object to client
        imageOutput.writeObject(item.getItemImage());
    }
    catch (IOException ioEx)
    {
        //alert server console
        System.out.println("\nUnable to send image for item "
                        + item.getItemCode() + " to "
                        + bidderName + "!");
        //no exit from system
        //bidding can still continue
    }
}

因此,每次有请求时,都会使用//to be displayed on GUI private static void receiveItemImage() { try { //wrap ObjectInputStream around socket //to receive objects sent from server ObjectInputStream imageInput = new ObjectInputStream(socket.getInputStream()); //read in image and store in ImageIcon instance image = (ImageIcon) imageInput.readObject(); //re-create label object to be blank imageLabel = new JLabel(); //remove label containing last image imagePanel.remove(imageLabel); //just ignores command if it does not already contain image //apply image to label imageLabel.setIcon(image); //apply image to CENTER of panel imagePanel.add(imageLabel, BorderLayout.CENTER); } //problem in input stream catch (IOException ioEx) { //alert user JOptionPane.showMessageDialog( null, "Error receiving image!"); //allow system to continue //no exit } //problem casting to ImageIcon type catch (ClassNotFoundException cnfEx) { //alert user JOptionPane.showMessageDialog( null, "Error converting Object to ImageIcon!"); //allow system to continue //no exit } } / ObjectOutpuStream创建ObjectInputStreamsocket.getOutputStream来处理图片的传递。

当客户端连接到服务器时,首先调用这些方法,并自动发送第一个图像和一组详细信息。这样可以正常工作,但是在整个程序中请求映像的任何后续尝试都会导致满足socket.getInputStream子句,并显示上面显示的错误消息。

我不能为我的生活找出原因,为什么它会在第一次工作但不会在此之后再次工作。如果有人能指出我正确的方向,那就太棒了!

谢谢, 标记

1 个答案:

答案 0 :(得分:1)

你应该只包一次流。在这种情况下,您无法再次将其包装,因为这对于对象流不起作用。

只打包一次流后,请在发送图像后致电ObjectOutputStream.reset()。如果你不这样做,它只会再次传递对象的引用(并使用大量内存)