import java.io.*;
import java.net.*;

class TCPServerSend {

  public static void main(String argv[]) throws Exception {
    ServerSocket welcomeSocket = new ServerSocket(6789);

    while (true) {
      System.out.print("Waiting for new Connection...\n");
      Socket connectionSocket = welcomeSocket.accept();
      // keine Verzögerung beim Senden von kleinen Datenmengen (hier unnötig)
      // connectionSocket.setTcpNoDelay(true);
      InputStream inFromClient = connectionSocket.getInputStream();
      // you can return objects for interfaces and abstract classes without declaring a new class
      // InputStream in= new InputStream(){public int read(){return 0;}};
      // Bytestream für Fileoutput
      FileOutputStream fileOut = new FileOutputStream("alice.ext");

      byte[] buffer = new byte[1024];

      while (connectionSocket.isConnected()) {
        // Lesen in Puffer, max. Zeichenzahl gleich Puffergröße, Rückgabe akt. Anzahl
        int bytesRead = inFromClient.read(buffer);
        // Prüfung auf das Ende des Streams (Client hat Socket geschlossen)
        if (bytesRead == -1) {
          break;
        }
        fileOut.write(buffer, 0, bytesRead);
      }
      fileOut.close();
      connectionSocket.close();
    }
  }
} 
           
