Socket Programming for sharing content of file

Server-Client Program To Transfer Content Of File from Server To Client

As we know that as search on any site we are treated as a Client and the the one who reply to our request is treated as Server. When we send any request to the server, it compute some program and gives the desired reply to us.

Here I had posted one Client-Server program in which the content of the file is transfer from the server side to the client side.

Here for the successful execution of the program we have to make 4 file in one folder namely, 
Client.java: For client side coding
Server.java: For server side coding
Client.txt: Where the content are received from the server
Server.txt: Where the content are already stored for giving response for the client request.

Let take a view on the coding.

Note: All the files, 2 java file and 2 txt file should be in same folder otherwise the program will generate the error.

Note: The port number in both the file i.e. in client.java and server.java should be same otherwise it will generate the binding error.

Client.java

package file_transefer;

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

public class Client {
    public static void main(String[] args) throws IOException
    {
        Socket sc=new Socket("localhost",1142);
        FileOutputStream fout= new FileOutputStream("client.txt");
        DataInputStream din=new DataInputStream(sc.getInputStream());
        int r;
        while((r=din.read())!=-1)
        {
            fout.write((char)r);
        }
        sc.close();
    }
}

Server.java

package file_transfer;

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

class Server
{
    public static void main(String args[]) throws IOException
    {
        ServerSocket ss=new ServerSocket(1142);
        Socket sc=ss.accept();
        System.out.println("connected..........");
        FileInputStream fin=new FileInputStream("server.txt");
        DataOutputStream dout=new DataOutputStream(sc.getOutputStream());
        int r;
            while((r=fin.read())!=-1)
            {
                dout.write(r);
            }
            System.out.println("\nFile Tranfered Successfully.");
            sc.close();
            ss.close();
    }
}

Happy Coding :)

Comments

Popular posts from this blog

MultiSelection of Item in Recycler View

Upload Image From Android To Php Server

Merge Sort