user2040500
user2040500

Reputation:

sending image via socket without closing the socket

I created an application in which the server(desktop) sends data and files via socket to multiple clients on android which are connected and all client socket objects are stored in a hashset.

Now the problem is when I send the data it works fine but in the case of sending images ,if we didn't close the socket the image wont reach the client. If socket is closed the images reaches to the client but if when the socket is closed, and when I tried to send some data or files again, Socket is closed exception is thrown.

Can we send images without closing socket? Can anyone please tell me some solutions for this

My code is as given below

BufferedImage bimg;
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      String iteamnam=iteamname.getText();
        try {
            int i= dbGetDet.insertDetails("INSERT INTO hotel_items (item,descs,status,section,imagename) VALUES ('"+iteamnam+"','null','active','pub','pizza.png')");
            if(i>0)
            {
            JOptionPane.showMessageDialog(rootPane, "<html><body>New Iteam Added</b></body></html>");
            fillIteams();
            fillSubIteams();
            TABhs = new CopyOnWriteArraySet(TABhs);
            System.out.println("Adding new Iteams Processing--------------------->"+TABhs.size());
            for(Iterator <Socket> it=TABhs.iterator();it.hasNext();)
            { 
                Socket so=it.next();
                PrintWriter ot = new PrintWriter(so.getOutputStream());
                ot.println("mainiteams#"+iteamnam+"#pizza.png#pub");
                ot.flush();
                bimg = ImageIO.read(new File("C:/div.png"));
                ImageIO.write(bimg,"PNG",so.getOutputStream());
                so.close(); //if close image will reach the client section (android)
            }
            }


        } catch (Exception ex) {
            Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }       

Upvotes: 0

Views: 1105

Answers (1)

pkuhar
pkuhar

Reputation: 601

Sockets are buffered(and data is actually sent in packets over the network). You'd need to flush on the stream to push the whole image out. Try:

OutputStream os = so.getOutputStream();
PrintWriter ot = new PrintWriter(os);
ot.println("mainiteams#"+iteamnam+"#pizza.png#pub");
ot.flush();
bimg = ImageIO.read(new File("C:/div.png"));
ImageIO.write(bimg,"PNG",os);
os.flush()

Upvotes: 2

Related Questions