JAVA FILE TRANSFER USING UDP

AIM:
        To send a document from client system to server system using net package of  java.
PROCEDURE:
1) Start the program.
2) Write program for client program.
3) Inside client package use objects of DatagramSocket class and DatagramPacket  class.
4) In server program by creating object for FileInputStream transfer data from file to byte array.
5) Using object of DatagramPacket class send the byte array to the client system.
6) Run client program then run server program.
7) Get the output.
8) Stop the program.



SOURCE CODE:
/*CLIENT CLASS*/
import java.net.*;
import java.io.*;
public class client
{
            public static void main(String args[])throws Exception
            {         
                        byte b[]=new byte[1024];
                        FileInputStream f=new FileInputStream("D:/raj.txt");
                        DatagramSocket dsoc=new DatagramSocket(2000);
                        int i=0;
                        while(f.available()!=0)
                        {
                                    b[i]=(byte)f.read();
                                    i++;
                        }                     
                        f.close();
                        dsoc.send(new DatagramPacket(b,i,InetAddress.getLocalHost(),1000));
            }

}

/*SERVER CLASS*/
import java.net.*;
import java.io.*;
public class server
{
            public static void main(String args[])throws IOException
            {
                        byte b[]=new byte[3072];
                        DatagramSocket dsoc=new DatagramSocket(1000);
                        FileOutputStream f=new FileOutputStream("D:/nandha.txt");
                        while(true)
                        {
                                    DatagramPacket dp=new DatagramPacket(b,b.length);
                                    dsoc.receive(dp);
                                    System.out.println(new String(dp.getData(),0,dp.getLength()));                             

                        }
            }
}


OUTPUT:
/*Client class*/
raj.txt
kanagaraj
D:\java\EXNO-7>java client
/*server class*/
D:\java\EXNO-7>java server
Kanagaraj

3 comments:

Paulis949 said...

Thank you. This program is good for .txt, but it doesn't work with another formats (.pdf, .mp4)

Anonymous said...

Sir,when I executing the client.java ,its getting out of terminal.Please help to complete the project.

Anonymous said...

I checked for bin, txt and jpg files it works well for them. Just remove .txt extension from server side.
Try increasing byte array size as pdf and mp4 are large files it might require huge array sizes.