rafikamal

Server

Aug 6th, 2014
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. import java.io.BufferedInputStream;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7.  
  8.  
  9. public class Server {
  10.     private static final int PORT = 5000;
  11.     private static final String FILE_NAME = "out.txt";
  12.     private static final int BUFFER_SIZE = 1024;
  13.    
  14.     public static void main(String[] args) {
  15.         try {
  16.             ServerSocket serverSocket = new ServerSocket(PORT);
  17.            
  18.             report("Waiting for connection..");
  19.             Socket connection = serverSocket.accept();
  20.            
  21.             report("Received connection from " + connection.getInetAddress().getHostName());
  22.             FileOutputStream output = new FileOutputStream(new File(FILE_NAME));
  23.             BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
  24.            
  25.             byte[] buffer = new byte[BUFFER_SIZE];
  26.             int bytesRead = -1;
  27.             while ((bytesRead = input.read(buffer, 0, buffer.length)) != -1) {
  28.                 output.write(buffer, 0, bytesRead);
  29.             }
  30.            
  31.             report("Write finished");
  32.            
  33.             output.close();
  34.             input.close();
  35.             connection.close();
  36.             serverSocket.close();
  37.         } catch (IOException e) {
  38.             e.printStackTrace();
  39.         }
  40.     }
  41.    
  42.     private static void report(String message) {
  43.         System.out.println(message);
  44.     }
  45. }
Add Comment
Please, Sign In to add comment