Implement TCP Server for transferring files using Socket and ServerSocket code example

Example: Implement TCP Server for transferring files using Socket and ServerSocket

//Client
import java.io.*;
import java.net.*;

public class Client {

    public static void main(String[] args) throws Exception {
        Socket s = new Socket("127.0.0.1", 1234);
        if (s.isConnected()) {
            System.out.println("Connected to server");
        }
        FileOutputStream fout = new FileOutputStream("received.txt");
        DataInputStream din = new DataInputStream(s.getInputStream());
        int r;
        while ((r = din.read()) != -1) {
            fout.write((char) r);
        }
        s.close();
    }

}

//Server
import java.io.*;
import java.net.*;

class Server {
    public static void main(String args[]) throws Exception {
        ServerSocket ss = new ServerSocket(1234);
        Socket s = ss.accept();
        System.out.println("connected..........");
        FileInputStream fin = new FileInputStream("Send.txt");
        DataOutputStream dout = new DataOutputStream(s.getOutputStream());
        int r;
        while ((r = fin.read()) != -1) {
            dout.write(r);

        }
        System.out.println("\nFiletranfer Completed");
        s.close();
        ss.close();
    }
}

Tags:

Misc Example