Friday, January 21, 2011

How to transfer a JPEG file from client to server using sockets JAVA

I searched on Google about this topic few days back. But I could not found a complete solution.Finally I came up with a solution. These methods from my client and server class shows it.


Client Part

 public void uploadFile(File f){
         try {
                socket=new Socket("127.0.0.1", 4000);
                BufferedInputStream in=new BufferedInputStream(new FileInputStream(f));
                byte[] buffer = new byte[(int)f.length()];
                in.read(buffer, 0, buffer.length);
                OutputStream os = socket.getOutputStream();
                os.write(buffer, 0, buffer.length);
                os.flush();
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
     }

Server Part

private void stroreFile() {
        try {
            byte[] mybytearray = new byte[1024];
            InputStream is = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream("recieved.jpg");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int bytesRead =0;
            while(bytesRead!=-1){
                bytesRead = is.read(mybytearray, 0, mybytearray.length);
                System.out.println(bytesRead);
                if(bytesRead!=-1)
                    bos.write(mybytearray, 0, bytesRead);
            }
            bos.close();
            fos.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

This works for gif and png files on the client side too. But those are saved at the server as  JPEG images. But that is not recommended.

Tuesday, January 4, 2011

How To show a splash screen in a GUI based JAVA program @ startup

Splash screens are essential things in todyas GUI softwares. We can use them to make our software attractive and show our details. This is how it's done.
First Create your splash screen as a image(eg-gif)
Then go to your netbeans or eclipse project folder of your GUI program, using Windows explorer or a similar software.
Find the file named manifest.mf and open it using a text editing software like notepad or gedit.
Add the following line to the end and save.
SplashScreen-Image: filename.gif
Now copy and paste the splash screen (filename.gif) to the folder called src
Then build your project using netbeans or eclipse and create a jar file.
When you open your software by double clicking the jar file splash screen can be seen.
This worked on me in netbeans.