6/15/2012

sending image object through socket in java classic example


easywayprogramming.com sending image object through socket in java classic example 

       Sending image through socket connection in java is not so difficult task. Many peoples found it difficult to do it. many times we need to send images through network socket from one computer to another computer. Now we are going to see how we can send image through socket in java. It is very interesting.

client side coding:
GreetingClient.java
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.imageio.*;

public class GreetingClient
{
    Image newimg;
    BufferedImage bimg;
    byte[] bytes;

   public static void main(String [] args)
   {
      String serverName = "localhost";
      int port = 6066;
      try
      {
         System.out.println("Connecting to " + serverName
                             + " on port " + port);
         Socket client = new Socket(serverName, port);

         System.out.println("Just connected to "
                      + client.getRemoteSocketAddress());

        DataInputStream in=new DataInputStream(client.getInputStream());
        System.out.println(in.readUTF());
        System.out.println(in.readUTF());

         DataOutputStream out =
                       new DataOutputStream(client.getOutPutStream());

         out.writeUTF("Hello from "
                      + client.getLocalSocketAddress());
         out.writeUTF("client: hello to server")

         ImageIcon img1=new ImageIcon("Ashish.jpg");
         Image img = img1.getImage();
         Image newimg = img.getScaledInstance(100, 120,  java.awt.Image.SCALE_SMOOTH);
         ImageIcon newIcon = new ImageIcon(newimg);

         bimg = ImageIO.read(new File("D:\adi-siddhi\DSC02503.JPG"));

         ImageIO.write(bimg,"JPG",client.getOutputStream());
         System.out.println("Image sent!!!!");
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

severside coding:
GreetingSever.java
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread
{
       private ServerSocket serverSocket;
       Socket server;

       public GreetingServer(int port) throws IOException, SQLException, ClassNotFoundException, Exception
       {
          serverSocket = new ServerSocket(port);
          serverSocket.setSoTimeout(180000);
       }

       public void run()
       {
           while(true)
          {
               try
               {
                  server = serverSocket.accept();
                  DataInputStream din=new DataInputStream(server.getInputStream());
                  DataOutputStream dout=new DataOutputStream(server.getOutputStream());

                  dout.writeUTF("server: -i am greeting server");
                  dout.writeUTF("server:- hi! hello client");

                  System.out.println(din.readUTF());
                  System.out.println(din.readUTF());

                  BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(socket.getInputStream()));

                  System.out.println("Image received!!!!");
                  //lblimg.setIcon(img);
              }
             catch(SocketTimeoutException st)
             {
                   System.out.println("Socket timed out!");
                  break;
             }
             catch(IOException e)
             {
                  e.printStackTrace();
                  break;
             }
             catch(Exception ex)
            {
                  System.out.println(ex);
            }
          }
       }
      
       public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception
       {
              //int port = Integer.parseInt(args[0]);
              Thread t = new GreetingServer(6066);
              t.start();
       }
}

Run the program as it is. first run greetingserver. java,  then greetingclient.java.

http://easywayprogramming.com/Java/sending-image-object-through-socket-in-java-classic-example.aspx?code=6&lan=j 

Follow the important rules given in post

30 comments:

  1. how to send more than one image through socket...?

    Using this code i can send one image successfuly, but not able to send another image.. :(
    Help plz....

    ReplyDelete
    Replies
    1. Hey povs937!
      This code is for sending on eimage at a time.
      If u want to send more than one image at a time,
      u can use loop or can create more than one buffered image object.
      When u send one image close the client socket. At the time of sending next image create new socket every time and close that socket every time.

      I f get new efficient code i will tell u!
      if u have any query u can reply me.

      Delete
    2. I want to create an application of java server to share screenshots of the screen to the android client much as a screensharing application can you help me with this?

      Delete
  2. what a function of this code??

    ImageIcon img1=new ImageIcon("Ashish.jpg");
    Image img = img1.getImage();
    Image newimg = img.getScaledInstance(100, 120, java.awt.Image.SCALE_SMOOTH);
    ImageIcon newIcon = new ImageIcon(newimg);

    ReplyDelete
    Replies
    1. Hey,
      this code is for scalling image.
      Means we use images as background to controls like panel, buttons, labels.
      But due to size of image it not fits properly on that control. So using above code we can change size of image!

      Delete
  3. I am getting error in ImageIcon when i run this program. Will u plzzz help me

    ReplyDelete
  4. I dont want to be that correct but you´ve got a spelling error you worte .getOutPutStream correctly it´s .getOutputStream just if sb is trying to copy your code you should fix it :)

    ReplyDelete





  5. i have converted images into text files and want to send the files. plz provide me the code.














    i have converted images into text files and want to send. plz provide me the code for sending files


    ReplyDelete
  6. img=ImageIO.read(ImageIO.createImageInputStream(socket.getInputStream()));


    this statement is wrong it shd be img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));

    ReplyDelete
  7. how can I send/receive file_name with file ?

    ReplyDelete
    Replies
    1. Hi Harikesh!!!
      As in code u can send image object, u can also send strings through socket!!!

      Delete
  8. Where the image is getting stored after client sent it??

    I've separated the programs as client and server in different folder.....
    Console is printing "Image sent" and "image recieved" msgs....but I do not know where the image is getting stored when client program sent it?? I've checked the server folder....but image is not getting stored over there.

    ReplyDelete
    Replies
    1. Hi Aniruddha!!
      Image is get stored in BufferedImage object named img. If u want you can store that image in database or show it on label, jpanel, jfarme.
      If u want to store that image physically in folder on server diskspace, u have to add code for that logic at server side code.

      Delete
  9. Hello am very new to socket programming while compiling GreetingServer.java i got many errors.The comman error is cannot find symbol in lines 11 13 33 55. Please help me

    ReplyDelete
  10. can you please write a code for sending multiple images

    ReplyDelete
  11. Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision. 
    Best Devops Training in pune
    Best Devops Training institute in Chennai

    ReplyDelete
  12. Nice tips. Very innovative... Your post shows all your effort and great experience towards your work Your Information is Great if mastered very well.
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  13. Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.sap training in bangalore

    ReplyDelete
  14. Linking is very useful thing.you have really helped lots of people who visit blog and provide them use full information.microsoft training in bangalore

    ReplyDelete
  15. How can you do that and display the received image into imageview?

    ReplyDelete


  16. This post is so interactive and informative.keep update more information...
    Java Training in Bangalore
    Java Classes in Pune

    ReplyDelete
  17. This post is so helpfull and informative.keep updating with more information...
    Uses Of Hacking
    Technical Hacking

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. Great, post is so informative and helpfull to everyone , keep posting and checkout my blog java course in pune

    ReplyDelete