├── .gitignore ├── README.md ├── TCPClient.java └── TCPServer.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | server/ 3 | client/ 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TCP-File-Transfer 2 | 3 | This is a Java application that : 4 | 5 | - uses TCP for file transfer. 6 | 7 | - has a user interface buit using Java AWT and Java Swing. 8 | 9 | - is built using Java Socket Programming. 10 | 11 | - allows multiple users to connect to a server at once. It accomplishes this through multithreading. 12 | 13 | - mandates the server to specify working directory as a command line argument with the freedom to specify a custom port number as the second argument. The default port number has been set to 3333. 14 | 15 | - server assigns connection IDs to the clients connected. 16 | 17 | - mandates client to specify working directory as a command line argument. It allows user to specify host address and if not specified, defaults it to Localhost. The user can also specify the port number as the third argument. 18 | 19 | - Displays files and directories present in the server working directory and allows the client to select files and download them onto the client system. 20 | 21 | - Allows the client to upload files to the server working directory. This allows 2 clients to transfer files through the server. 22 | 23 | - You may call it ShareIt, Xender or something similar for laptops and PCs :wink: 24 | 25 | 26 | ## Getting Started 27 | ``` 28 | git clone https://github.com/mansimarkaur/TCP-file-transfer 29 | cd TCP-file-transfer 30 | ``` 31 | For *server* : 32 | ``` 33 | javac TCPServer.java 34 | java TCPServer 35 | ``` 36 | 37 | For *client* : 38 | ``` 39 | javac TCPClient.java 40 | java TCPClient 41 | ``` 42 | Enter file name and click on **upload**. :arrow_up: 43 | 44 | Choose file to be downloaded from the panel and click on **download**. :arrow_down: 45 | 46 | **Server and Client can interact only through the same port number** 47 | 48 | ## Prerequisites 49 | 50 | If you do not have Java installed, refer to this [Java installation guide](https://www.java.com/en/download/help/download_options.xml) 51 | 52 | *For newbies, remember to set path variables in Windows and OSX* 53 | -------------------------------------------------------------------------------- /TCPClient.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.net.*; 3 | import java.lang.*; 4 | import java.awt.*; 5 | import java.awt.event.*; 6 | import javax.swing.*; 7 | import java.util.Arrays; 8 | 9 | class TCPClient extends JFrame implements ActionListener, MouseListener { 10 | JPanel panel; 11 | JLabel title, subT, msg, error, servFiles; 12 | Font font,labelfont; 13 | JTextField txt; 14 | JButton up, down; 15 | String dirName; 16 | Socket clientSocket; 17 | InputStream inFromServer; 18 | OutputStream outToServer; 19 | BufferedInputStream bis; 20 | PrintWriter pw; 21 | String name, file, path; 22 | String hostAddr; 23 | int portNumber; 24 | int c; 25 | int size = 9022386; 26 | JList filelist; 27 | String[] names = new String[10000]; 28 | int len; // number of files on the server retrieved 29 | 30 | public TCPClient(String dir, String host, int port) { 31 | super("TCP CLIENT"); 32 | 33 | // set dirName to the one that's entered by the user 34 | dirName = dir; 35 | 36 | // set hostAddr to the one that's passed by the user 37 | hostAddr = host; 38 | 39 | // set portNumber to the one that's passed by the user 40 | portNumber = port; 41 | 42 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 43 | 44 | panel = new JPanel(null); 45 | 46 | font = new Font("Roboto", Font.BOLD, 60); 47 | title = new JLabel("TCP CLIENT"); 48 | title.setFont(font); 49 | title.setBounds(300, 50, 400, 50); 50 | panel.add(title); 51 | 52 | labelfont = new Font("Roboto", Font.PLAIN, 20); 53 | subT = new JLabel("Enter File Name :"); 54 | subT.setFont(labelfont); 55 | subT.setBounds(100, 450, 200, 50); 56 | panel.add(subT); 57 | 58 | txt = new JTextField(); 59 | txt.setBounds(400, 450, 500, 50); 60 | panel.add(txt); 61 | 62 | up = new JButton("Upload"); 63 | up.setBounds(250, 550, 200, 50); 64 | panel.add(up); 65 | 66 | down = new JButton("Download"); 67 | down.setBounds(550, 550, 200, 50); 68 | panel.add(down); 69 | 70 | error = new JLabel(""); 71 | error.setFont(labelfont); 72 | error.setBounds(200, 650, 600, 50); 73 | panel.add(error); 74 | 75 | up.addActionListener(this); 76 | down.addActionListener(this); 77 | 78 | try { 79 | clientSocket = new Socket(hostAddr, portNumber); 80 | inFromServer = clientSocket.getInputStream(); 81 | pw = new PrintWriter(clientSocket.getOutputStream(), true); 82 | outToServer = clientSocket.getOutputStream(); 83 | ObjectInputStream oin = new ObjectInputStream(inFromServer); 84 | String s = (String) oin.readObject(); 85 | System.out.println(s); 86 | 87 | len = Integer.parseInt((String) oin.readObject()); 88 | System.out.println(len); 89 | 90 | String[] temp_names = new String[len]; 91 | 92 | for(int i = 0; i < len; i++) { 93 | String filename = (String) oin.readObject(); 94 | System.out.println(filename); 95 | names[i] = filename; 96 | temp_names[i] = filename; 97 | } 98 | 99 | // sort the array of strings that's going to get displayed in the scrollpane 100 | Arrays.sort(temp_names); 101 | 102 | servFiles = new JLabel("Files in the Server Directory :"); 103 | servFiles.setBounds(350, 125, 400, 50); 104 | panel.add(servFiles); 105 | 106 | filelist = new JList<>(temp_names); 107 | JScrollPane scroll = new JScrollPane(filelist); 108 | scroll.setBounds(300, 200, 400, 200); 109 | 110 | panel.add(scroll); 111 | filelist.addMouseListener(this); 112 | 113 | } 114 | catch (Exception exc) { 115 | System.out.println("Exception: " + exc.getMessage()); 116 | error.setText("Exception:" + exc.getMessage()); 117 | error.setBounds(300,125,600,50); 118 | panel.revalidate(); 119 | } 120 | 121 | getContentPane().add(panel); 122 | } 123 | 124 | public void mouseClicked(MouseEvent click) { 125 | if (click.getClickCount() == 2) { 126 | String selectedItem = (String) filelist.getSelectedValue(); 127 | txt.setText(selectedItem); 128 | panel.revalidate(); 129 | } 130 | } 131 | 132 | public void mousePressed(MouseEvent e){} 133 | public void mouseEntered(MouseEvent e){} 134 | public void mouseExited(MouseEvent e){} 135 | public void mouseReleased(MouseEvent e){} 136 | 137 | public void actionPerformed(ActionEvent event) { 138 | if (event.getSource() == up) { 139 | try { 140 | name = txt.getText(); 141 | 142 | FileInputStream file = null; 143 | BufferedInputStream bis = null; 144 | 145 | boolean fileExists = true; 146 | path = dirName + name; 147 | 148 | try { 149 | file = new FileInputStream(path); 150 | bis = new BufferedInputStream(file); 151 | } catch (FileNotFoundException excep) { 152 | fileExists = false; 153 | System.out.println("FileNotFoundException:" + excep.getMessage()); 154 | error.setText("FileNotFoundException:" + excep.getMessage()); 155 | panel.revalidate(); 156 | } 157 | 158 | if (fileExists) { 159 | // send file name to server 160 | pw.println(name); 161 | 162 | System.out.println("Upload begins"); 163 | error.setText("Upload begins"); 164 | panel.revalidate(); 165 | 166 | // send file data to server 167 | sendBytes(bis, outToServer); 168 | System.out.println("Completed"); 169 | error.setText("Completed"); 170 | panel.revalidate(); 171 | 172 | boolean exists = false; 173 | for(int i = 0; i < len; i++){ 174 | if(names[i].equals(name)){ 175 | exists = true; 176 | break; 177 | } 178 | } 179 | 180 | if(!exists){ 181 | names[len] = name; 182 | len++; 183 | } 184 | 185 | String[] temp_names = new String[len]; 186 | for(int i = 0; i < len; i++){ 187 | temp_names[i] = names[i]; 188 | } 189 | 190 | // sort the array of strings that's going to get displayed in the scrollpane 191 | Arrays.sort(temp_names); 192 | 193 | // update the contents of the list in scroll pane 194 | filelist.setListData(temp_names); 195 | 196 | // close all file buffers 197 | bis.close(); 198 | file.close(); 199 | outToServer.close(); 200 | } 201 | } 202 | catch (Exception exc) { 203 | System.out.println("Exception: " + exc.getMessage()); 204 | error.setText("Exception:" + exc.getMessage()); 205 | panel.revalidate(); 206 | } 207 | } 208 | else if (event.getSource() == down) { 209 | try { 210 | File directory = new File(dirName); 211 | 212 | if (!directory.exists()) { 213 | directory.mkdir(); 214 | } 215 | boolean complete = true; 216 | byte[] data = new byte[size]; 217 | name = txt.getText(); 218 | file = new String("*" + name + "*"); 219 | pw.println(file); //lets the server know which file is to be downloaded 220 | 221 | ObjectInputStream oin = new ObjectInputStream(inFromServer); 222 | String s = (String) oin.readObject(); 223 | 224 | if(s.equals("Success")) { 225 | File f = new File(directory, name); 226 | FileOutputStream fileOut = new FileOutputStream(f); 227 | DataOutputStream dataOut = new DataOutputStream(fileOut); 228 | 229 | //empty file case 230 | while (complete) { 231 | c = inFromServer.read(data, 0, data.length); 232 | if (c == -1) { 233 | complete = false; 234 | System.out.println("Completed"); 235 | error.setText("Completed"); 236 | panel.revalidate(); 237 | 238 | } else { 239 | dataOut.write(data, 0, c); 240 | dataOut.flush(); 241 | } 242 | } 243 | fileOut.close(); 244 | } 245 | else { 246 | System.out.println("Requested file not found on the server."); 247 | error.setText("Requested file not found on the server."); 248 | panel.revalidate(); 249 | } 250 | } 251 | catch (Exception exc) { 252 | System.out.println("Exception: " + exc.getMessage()); 253 | error.setText("Exception:" + exc.getMessage()); 254 | panel.revalidate(); 255 | } 256 | } 257 | } 258 | 259 | private static void sendBytes(BufferedInputStream in , OutputStream out) throws Exception { 260 | int size = 9022386; 261 | byte[] data = new byte[size]; 262 | int bytes = 0; 263 | int c = in.read(data, 0, data.length); 264 | out.write(data, 0, c); 265 | out.flush(); 266 | } 267 | 268 | public static void main(String args[]) { 269 | // if at least three argument are passed, consider the first one as directory path, 270 | // the second one as host address and the third one as port number 271 | // If host address is not present, default it to "localhost" 272 | // If port number is not present, default it to 3333 273 | // If directory path is not present, show error 274 | if(args.length >= 3){ 275 | TCPClient tcp = new TCPClient(args[0], args[1], Integer.parseInt(args[2])); 276 | tcp.setSize(1000, 900); 277 | tcp.setVisible(true); 278 | } 279 | else if(args.length == 2){ 280 | TCPClient tcp = new TCPClient(args[0], args[1], 3333); 281 | tcp.setSize(1000, 900); 282 | tcp.setVisible(true); 283 | } 284 | else if(args.length == 1){ 285 | TCPClient tcp = new TCPClient(args[0], "localhost", 3333); 286 | tcp.setSize(1000, 900); 287 | tcp.setVisible(true); 288 | } 289 | else { 290 | System.out.println("Please enter the client directory address as first argument while running from command line."); 291 | } 292 | } 293 | } 294 | -------------------------------------------------------------------------------- /TCPServer.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.net.*; 3 | import java.util.*; 4 | 5 | public class TCPServer { 6 | public static void main(String args[]) throws Exception { 7 | // if at least two argument are passed, consider the first one as directory path 8 | // and the second one as port number 9 | // If port number is not present, default it to 3333 10 | // If directory path is not present, show error 11 | if(args.length == 0) { 12 | System.out.println("Please enter the server directory address as first argument while running from command line."); 13 | } 14 | else { 15 | int id = 1; 16 | System.out.println("Server started..."); 17 | System.out.println("Waiting for connections..."); 18 | 19 | ServerSocket welcomeSocket; 20 | 21 | // port number is passed by the user 22 | if(args.length >= 2){ 23 | welcomeSocket = new ServerSocket(Integer.parseInt(args[1])); 24 | } 25 | else{ 26 | welcomeSocket = new ServerSocket(3333); 27 | } 28 | 29 | while (true) { 30 | Socket connectionSocket = welcomeSocket.accept(); 31 | System.out.println("Client with ID " + id + " connected from " + connectionSocket.getInetAddress().getHostName() + "..."); 32 | Thread server = new ThreadedServer(connectionSocket, id, args[0]); 33 | id++; 34 | server.start(); 35 | } 36 | } 37 | } 38 | } 39 | 40 | class ThreadedServer extends Thread { 41 | int n; 42 | int m; 43 | String name, f, ch, fileData; 44 | String filename; 45 | Socket connectionSocket; 46 | int counter; 47 | String dirName; 48 | 49 | public ThreadedServer(Socket s, int c, String dir) { 50 | connectionSocket = s; 51 | counter = c; 52 | 53 | // set dirName to the one that's entered by the user 54 | dirName = dir; 55 | } 56 | 57 | public void run() { 58 | try { 59 | BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); 60 | InputStream inFromClient = connectionSocket.getInputStream(); 61 | PrintWriter outPw = new PrintWriter(connectionSocket.getOutputStream()); 62 | OutputStream output = connectionSocket.getOutputStream(); 63 | 64 | ObjectOutputStream oout = new ObjectOutputStream(output); 65 | oout.writeObject("Server says Hi!"); 66 | 67 | File ff = new File(dirName); 68 | ArrayList names = new ArrayList(Arrays.asList(ff.list())); 69 | int len = names.size(); 70 | oout.writeObject(String.valueOf(names.size())); 71 | 72 | for(String name: names) { 73 | oout.writeObject(name); 74 | } 75 | 76 | name = in.readLine(); 77 | ch = name.substring(0, 1); 78 | 79 | if (ch.equals("*")) { 80 | n = name.lastIndexOf("*"); 81 | filename = name.substring(1, n); 82 | FileInputStream file = null; 83 | BufferedInputStream bis = null; 84 | boolean fileExists = true; 85 | System.out.println("Request to download file " + filename + " recieved from " + connectionSocket.getInetAddress().getHostName() + "..."); 86 | filename = dirName + filename; 87 | //System.out.println(filename); 88 | try { 89 | file = new FileInputStream(filename); 90 | bis = new BufferedInputStream(file); 91 | } 92 | catch (FileNotFoundException excep) { 93 | fileExists = false; 94 | System.out.println("FileNotFoundException:" + excep.getMessage()); 95 | } 96 | if (fileExists) { 97 | oout = new ObjectOutputStream(output); 98 | oout.writeObject("Success"); 99 | System.out.println("Download begins"); 100 | sendBytes(bis, output); 101 | System.out.println("Completed"); 102 | bis.close(); 103 | file.close(); 104 | oout.close(); 105 | output.close(); 106 | } 107 | else { 108 | oout = new ObjectOutputStream(output); 109 | oout.writeObject("FileNotFound"); 110 | bis.close(); 111 | file.close(); 112 | oout.close(); 113 | output.close(); 114 | } 115 | } 116 | else{ 117 | try { 118 | boolean complete = true; 119 | System.out.println("Request to upload file " + name + " recieved from " + connectionSocket.getInetAddress().getHostName() + "..."); 120 | File directory = new File(dirName); 121 | if (!directory.exists()) { 122 | System.out.println("Dir made"); 123 | directory.mkdir(); 124 | } 125 | 126 | int size = 9022386; 127 | byte[] data = new byte[size]; 128 | File fc = new File(directory, name); 129 | FileOutputStream fileOut = new FileOutputStream(fc); 130 | DataOutputStream dataOut = new DataOutputStream(fileOut); 131 | 132 | while (complete) { 133 | m = inFromClient.read(data, 0, data.length); 134 | if (m == -1) { 135 | complete = false; 136 | System.out.println("Completed"); 137 | } else { 138 | dataOut.write(data, 0, m); 139 | dataOut.flush(); 140 | } 141 | } 142 | fileOut.close(); 143 | } catch (Exception exc) { 144 | System.out.println(exc.getMessage()); 145 | } 146 | } 147 | } 148 | catch (Exception ex) { 149 | System.out.println(ex.getMessage()); 150 | } 151 | } 152 | 153 | private static void sendBytes(BufferedInputStream in , OutputStream out) throws Exception { 154 | int size = 9022386; 155 | byte[] data = new byte[size]; 156 | int bytes = 0; 157 | int c = in .read(data, 0, data.length); 158 | out.write(data, 0, c); 159 | out.flush(); 160 | } 161 | } 162 | --------------------------------------------------------------------------------