Java File Transfer Example Using Socket

Date: 21 January 2015
Views: 3098
This code snippet demonstrates a very simple file transfer program. In this example the client program sends a file to the server. The client program is a GUI and allows a user to browse for a file to send to the server.
  1. // Client.java  
  2.    
  3. /*  
  4.  * In this client/server example, the client sends a file to the server.  
  5.  *  
  6.  */  
  7.    
  8. import javax.swing.*;  
  9. import java.awt.*;  
  10. import java.awt.event.*;  
  11. import java.net.*;  
  12. import java.io.*;  
  13.    
  14. public class Client extends JFrame implements ActionListener {  
  15.    
  16.     private JTextField txtFile;  
  17.      
  18.     public static void main(String args[]){  
  19.    
  20.         /* Create and display the client form */  
  21.    
  22.         Client clientForm = new Client();  
  23.         clientForm.Display();  
  24.     }  
  25.    
  26.     public void Display(){  
  27.    
  28.         JFrame frame = new JFrame();  
  29.         frame.setTitle("Client");  
  30.    
  31.         FlowLayout layout = new FlowLayout();  
  32.         layout.setAlignment(FlowLayout.LEFT);  
  33.    
  34.         JLabel lblFile = new JLabel("Filename:");  
  35.          
  36.         txtFile = new JTextField();  
  37.         txtFile.setPreferredSize(new Dimension(150,30));  
  38.    
  39.         JButton btnTransfer = new JButton("Transfer");  
  40.         btnTransfer.addActionListener(this);  
  41.    
  42.         JPanel mainPanel = new JPanel();  
  43.         mainPanel.setLayout(layout);  
  44.         mainPanel.add(lblFile);  
  45.         mainPanel.add(txtFile);  
  46.         mainPanel.add(btnTransfer);  
  47.    
  48.         frame.getContentPane().add(mainPanel);  
  49.         frame.pack();  
  50.         frame.setVisible(true);  
  51.     }  
  52.    
  53.     public void actionPerformed(ActionEvent e) {  
  54.    
  55.         /* File Open Dialog box allows the user to select a file */  
  56.    
  57.         JFileChooser fileDlg = new JFileChooser();  
  58.         fileDlg.showOpenDialog(this);  
  59.         String filename = fileDlg.getSelectedFile().getAbsolutePath();  
  60.         txtFile.setText(filename);  
  61.    
  62.         try{  
  63.    
  64.             /* Try to connect to the server on localhost, port 5555 */  
  65.    
  66.             Socket sk = new Socket("localhost", 5555);  
  67.             OutputStream output = sk.getOutputStream();  
  68.    
  69.             /* Send filename to server */  
  70.    
  71.             OutputStreamWriter outputStream = new OutputStreamWriter(sk.getOutputStream());  
  72.             outputStream.write(fileDlg.getSelectedFile().getName() + "\n");  
  73.             outputStream.flush();  
  74.    
  75.             /* Get reponse from server */  
  76.    
  77.             BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));  
  78.    
  79.             String serverStatus = inReader.readLine(); // Read the first line  
  80.    
  81.             /* If server is ready, send the file */  
  82.    
  83.             if ( serverStatus.equals("READY") ){  
  84.    
  85.                 FileInputStream file = new FileInputStream(filename);  
  86.    
  87.                 byte[] buffer = new byte[sk.getSendBufferSize()];  
  88.    
  89.                 int bytesRead = 0;  
  90.    
  91.                 while((bytesRead = file.read(buffer))>0)  
  92.                 {  
  93.                     output.write(buffer,0,bytesRead);  
  94.                 }  
  95.    
  96.                 output.close();  
  97.                 file.close();  
  98.                 sk.close();  
  99.    
  100.                 JOptionPane.showMessageDialog(this"Transfer complete");  
  101.             }  
  102.         }  
  103.         catch (Exception ex){  
  104.             /* Catch any errors */  
  105.             JOptionPane.showMessageDialog(this, ex.getMessage());  
  106.         }  
  107.     }  
  108. }  
  109.    
  110.    
  111. // Server.java  
  112.    
  113. /*  
  114.  * Server waits for a connection to be established by client  
  115.  *  
  116.  */  
  117.    
  118. import java.io.*;  
  119. import java.net.*;  
  120.    
  121. class Server  
  122. {  
  123.     public static void main(String args[])throws Exception  
  124.     {  
  125.         System.out.println("Server running...");  
  126.    
  127.         /* Listen on port 5555 */  
  128.    
  129.         ServerSocket server = new ServerSocket(5555);  
  130.    
  131.         /* Accept the sk */  
  132.    
  133.         Socket sk = server.accept();  
  134.          
  135.         System.out.println("Server accepted client");  
  136.         InputStream input = sk.getInputStream();  
  137.         BufferedReader inReader = new BufferedReader(new InputStreamReader(sk.getInputStream()));  
  138.         BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));  
  139.    
  140.         /* Read the filename */  
  141.         String filename = inReader.readLine();  
  142.    
  143.         if ( !filename.equals("") ){  
  144.    
  145.             /* Reply back to client with READY status */  
  146.    
  147.             outReader.write("READY\n");  
  148.             outReader.flush();  
  149.         }  
  150.    
  151.         /* Create a new file in the tmp directory using the filename */  
  152.         FileOutputStream wr = new FileOutputStream(new File("C://tmp/" + filename));  
  153.    
  154.         byte[] buffer = new byte[sk.getReceiveBufferSize()];  
  155.    
  156.         int bytesReceived = 0;  
  157.    
  158.         while((bytesReceived = input.read(buffer))>0)  
  159.         {  
  160.             /* Write to the file */  
  161.            wr.write(buffer,0,bytesReceived);  
  162.         }  
  163.     }  
  164. } 
ObjectInputStream And ObjectOutputStream Example
In the following code snippet, the server creates and serializes an object, which it then sends to a connected client. The client deserializes the object and displays its data to the console.
Simple POP3 Class
This code snippet presents a simple POP3 class that can be used to get emails.
Simple File Transfer Example
This code snippet demonstrates a simple file transfer. The client requests a file from the server and the server sends the file.
Simple Echo Server
The following code snippet demonstrates a simple echo server. The client sends the server a message and the server echos the message back to the client.
Client Server Example 1
The following code snippet demonstrates a simple client/server.