Search Tutorials

Wednesday 17 April 2013

Client Server Java code to send Text or Image File

Java program to send text or image file from client to server(receiver). In this program, more than one client can send text or image file to server. Run client and server program using command prompt, Both side GUI will open for communication.

Sender Program

import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

class Client implements ActionListener
{

    Socket s;
    DataInputStream din;
    DataOutputStream dout;
    String str;

//*******************************Client1 GUI*********************************//

    TextField tf;
    TextArea ta;
    Label lb;
    Button b;

    public Client()
    {

    Frame f=new Frame("Client");
    f.setLayout(new FlowLayout());
    f.setBackground(Color.orange);
    tf=new TextField(15);
    ta=new TextArea(12,20);
    ta.setBackground(Color.white);
    lb=new Label("Enter File Name To Be Send");
    b=new Button("Send");
    f.add(lb);
    f.add(tf);
    f.add(b);
    f.add(ta);
    ta.setBounds(200,200,10,10);
    f.addWindowListener(new W1());
    b.addActionListener(this);
    f.setSize(300,400);
    f.setLocation(300,300);
    f.setVisible(true);
    f.validate();

//*********************************GUI END*******************************//   



//********************************Creating Connection*********************//   


        try {   
        s=new Socket("localhost",7860);
        System.out.println(s);
        din=new DataInputStream(s.getInputStream());
        dout=new DataOutputStream(s.getOutputStream());
            }catch(Exception e)
                          {
                             System.out.println(e);
                          }
     
        }

    private class W1 extends WindowAdapter
     {
          public void windowClosing(WindowEvent we) 
          {
           System.exit(0);
          }
     }

//********************************************************************//

    public void actionPerformed(ActionEvent ae) 
     {
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      
          String fileName;
          if(ae.getSource()==b)
           {   
            fileName=tf.getText();

//*******************Coading for image transfer**********************//       
  
        int flag=0,i;
        String extn="";
            for(i=0;i<fileName.length();i++)
            {
                if(fileName.charAt(i)=='.' || flag==1)
                {
                flag=1;
                extn+=fileName.charAt(i);
                }
            }   
       
            if(extn.equals(".jpg") || extn.equals(".png"))
                {
                try{
               
                    File file = new File(fileName);
                    FileInputStream fin = new FileInputStream(file);   
                    dout.writeUTF(fileName);
                    System.out.println("Sending image...");
                    byte[] readData = new byte[1024];

                    while((i = fin.read(readData)) != -1)
                            {
                            dout.write(readData, 0, i);
                            }
                            System.out.println("Image sent");
                            ta.appendText("\nImage Has Been Sent");
                            fin.close();
                    }catch(IOException ex)
                      {System.out.println("Image ::"+ex);}
           
//*****************************Text File********************************//
                }               
            else
            {
           
            try{
            FileInputStream fstream = new FileInputStream(fileName);
              // Get the object of DataInputStream
              DataInputStream in = new DataInputStream(fstream);
              BufferedReader bcr = new BufferedReader(new InputStreamReader(in));
  
            dout.writeUTF(fileName);
            System.out.println("Sending File" + fileName);
            String s1;
                    ta.appendText("\n");
                    while((s1=bcr.readLine())!=null)
                    {
                    System.out.println(""+s1);
                    ta.appendText(s1+"\n");
                    dout.writeUTF(s1);
                    dout.flush();
                    Thread.currentThread().sleep(500);       
                
                    }
                }catch(Exception e){System.out.println("Enter Valid File Name");}
            }
         }
        }

    public static void main(String ar[])
    {
    Client object=new Client();
    }
}


Receiver program

import java.io.*;
import java.net.*;

class Server
{
static int i=0; 
private static int maxcon=0;
   
    public static void main(String args[])
    {
    try
        {
        ServerSocket ss;
        Socket s;

        System.out.println("Server Started");
        ss=new ServerSocket(7860);

            while((i++ < maxcon) || (maxcon == 0))
            {
            doComms connection;
            s=ss.accept();
            System.out.println(s);
            System.out.println("Client "+i+"  Connected");
            doComms conn_c= new doComms(s);
            Thread t = new Thread(conn_c);
            t.start();
            }
        } catch (IOException ioe) {
                                System.out.println("IOException on socket listen: " + ioe);
                                ioe.printStackTrace();
                                  }
                            
    }
}


class doComms implements Runnable 
{
    private Socket s;
   
    doComms(Socket s)
    {
      this.s=s;
    }

    public void run () 
    {

        try {
        // Get input from the client
            DataInputStream dis = new DataInputStream (s.getInputStream());
            PrintStream out1 = new PrintStream(s.getOutputStream());

            String str,extn="";
            str=dis.readUTF();
            System.out.println("\n"+str);
            int flag=0,i;
            
                for(i=0;i<str.length();i++)
                {
                    
                    if(str.charAt(i)=='.' || flag==1)
                    {
                    flag=1;
                    extn+=str.charAt(i);
                    }
                }
        
        
//**********************reading image*********************************//            
            
                if(extn.equals(".jpg") || extn.equals(".png"))
                  {            
                    File file = new File("RecievedImage"+str);
                    FileOutputStream fout = new FileOutputStream(file);
             
                    //receive and save image from client
                    byte[] readData = new byte[1024];
                    while((i = dis.read(readData)) != -1)
                    {
                        fout.write(readData, 0, i);
                        if(flag==1)
                        {
                        System.out.println("Image Has Been Received");
                        flag=0;
                        }
                    }
                fout.flush();
                fout.close();
 
            
            
//****************************Reading Other Files******************//            
                  }
                else
                {
                    FileWriter fstream = new FileWriter("ReceivedFile"+ str);
                    PrintWriter out=new PrintWriter(fstream);

                    do
                    {
                    str=dis.readUTF();
                    System.out.println(" "+str);
                    out.println(str);
                    out.flush();
                    if(str==null)break;
   
                    }while(true);
        
                    System.out.println("One File Received");
                    out.close();
                }
            } catch (IOException ioe) {
                System.out.println("");
                                      }
    }

}


If you have any doubt than comment and Share to improve this blog.

Related Programs:-

★ Java code to implement RSA Algorithm

★ Java code to implement MD5 Algorithm


★ C code to implement RSA Algorithm

★ Encrypt and Decrypt a message using Substitution Cipher

★ Encrypt and Decrypt a message using Vernan Cipher

10 comments:

  1. Hai Thank's for this ...
    I'm very pleased
    What's the for this project ???
    the name for the sender class and Receiver class ...
    I need this for my excercises ...


    ReplyDelete
    Replies
    1. Sever.java and Client.java ..it can send text as well as image.

      Delete
    2. hy thanks 4 ur reply
      i've already run this Program in eclipse but nothing Happen
      The java said the can not find the specified location
      I already copy the image address in to the text field and even i copied the file image in one folder with the client.java file i thought this program reading the image in the same folder
      But still nothing happen ...

      Pleasee
      Can you explain how to use this program
      Thanks B4 ...
      I'm newbie for java ...
      and this is for my exercises from my School ...

      Delete
    3. @Md Mohsin this program is not running

      Delete
  2. how this code will work...?

    ReplyDelete
  3. what would be the code if i wanted to send a sound file?

    ReplyDelete
  4. i want to send text file to my android device

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete
  6. i can send only file not text pls help

    ReplyDelete
  7. how do we view the image file at client? it just says image sent..wheres te image?

    ReplyDelete

Back to Top