# File über Socket lesen



## Zackwlg (29. Dez 2010)

Hallo,

ich versuche seit Tagen irgendeine Textdatei über eine Socketverbindung zu senden. Es sind drei Dateien: der Fileserver gibt das Verzeichnis vor (C und startet pro client eine Verbindung (ConnectionHandler). Der ConnectionHandler bietet für jede Verbindung seine Dienste an wie Verzeichnisinhalt anzeigen (index) oder Datei anzeigen (get). Die Anzeige des Verzeichnisinhalts über index funktioniert. Die Anzeige einer Datei beim client leider nicht. Mit einer while (true) Schleife versuche ich die Zeile zu zählen. Diese Anzahl soll dem Client übermittelt werden, womit er dann die Ausgabe über eine for Schleife steuern kann. Leider wird der Code im ConnectionHandler nach dieser while (true) Schleife nicht mehr erreicht. Das Problem ist also, dass ich die Ausgabe der Datei nicht hin bekomme. Ein Datei soll zeilenweise zum Client gesendet werden und dort zeilenweise angezeigt werden. Ich bin für jeden Tipp dankbar. Hier meine Dateien:

FileServer

```
import java.net.*;
  import java.io.*;

  public class FileServer {

    static final int LISTENING_PORT = 4020;

    public static void main(String[] args) {

      File directory; // Directory with privided Files
      ServerSocket listener; // Listens for connection requests.
      Socket connection; // A socket for communicating with a client.

      
      directory = new File("C:\\");
      
      // Check if directory is available 
      if ( ! directory.exists() ) {
        System.out.println("directory does not exist.");
        return;
      }
      if (! directory.isDirectory() ) {
        System.out.println("The file is not a directory.");
        return;
      }

      /* Listen for connection requests and then create a thread (ConnextionHandler)
         server is terminated by a CONTROL-C. */

      try {
        listener = new ServerSocket(LISTENING_PORT);
        System.out.println("Listening on port " + LISTENING_PORT);
        while (true) {
          connection = listener.accept();
          new ConnectionHandler(directory,connection);
        }
      }
      catch (Exception e) {
        System.out.println("Server shut down unexpectedly.");
        System.out.println("Error: " + e);
        return;
      }

  } 
  }
```


ConnectionHandler


```
import java.net.*;
import java.io.*;

class ConnectionHandler extends Thread {
     // a ConnectionHandler (thread) for each client

    File directory; // directory with provided files
    Socket connection; // client connection
    DataInputStream incoming; // reading data from the client
    PrintWriter outgoing; // sending data to the client
   

    ConnectionHandler(File dir, Socket conn) {
       // Constructor with connection and directory
    	
      directory = dir;
      connection = conn;
      start();
    }

    void sendIndex() throws Exception {
       // Send the content of the directory after an index command
      String[] fileList = directory.list();
      int flen = fileList.length;
      outgoing.write(flen);
      for (int i = 0; i < fileList.length; i++)
        outgoing.println(fileList[i]);
      outgoing.flush();
      outgoing.close();
      if (outgoing.checkError())
        throw new Exception("Error while transmitting data.");
    }

        
    
    void sendFile(String fileName) throws Exception {
       // send the content of the file after a get command
    	
      File file = new File(directory,fileName);
      
      
      if ( (! file.exists()) || file.isDirectory() ) {
         // check if file exists and is not a directory
        outgoing.println("error sendFile");
      }
      else {
    	  
        outgoing.println("ok sendFile");
        BufferedReader fileIn = new BufferedReader(new FileReader(file));
               
        int t = 0;
        while (true) {
            // count lines from the file
           String line = fileIn.readLine();
          t = t+1;
           }
        int k = t;    // this code is unreachable !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        outgoing.write(k); // for printing on client side for (int t = 0; t<flength;t ++) ...
                
               
        while (true) {
            // send lines from the file to the client
           String line = fileIn.readLine();
           outgoing.println(line);
           }
      }
      outgoing.flush();
      outgoing.close();
      if (outgoing.checkError())
        throw new Exception("Error while transmitting data."); 
    }

   
	public void run() {
       // thread method
       // build streams, processed client command index or get
      String command = "Command not read";
      
      try {
    	BufferedReader incoming  = new BufferedReader(new InputStreamReader( connection.getInputStream()));
        outgoing = new PrintWriter( connection.getOutputStream() );
        command = incoming.readLine();
        
        if (command.equals("index")) {
          sendIndex();
        }
        else if (command.startsWith("get")){
          String fileName = command.substring(3).trim();
          sendFile(fileName);
        }
        else {
          outgoing.println("unknown command");
          outgoing.flush();
        }
        System.out.println("OK " + connection.getInetAddress() + " " + command);
      }
      catch (Exception e) {
        System.out.println("ERROR " + connection.getInetAddress() + " " + command + " " + e);
      }
      finally {
        try {
          connection.close();
        }
        catch (IOException e) {
        }
      }
    }

   }
```


FileServerClient


```
import java.io.*;
import java.net.*;


public class FileServerClient{
	// the client
	
	public FileServerClient(String[] args){
		
		String host = "localhost";
		int port = 4020;
		
		//checks for args
		if(args.length == 2){
			host = args[0];
			port = Integer.parseInt(args[1]);
		}
		
		//build socket and streams
		try{
			Socket s = new Socket(host, port);
			System.out.println("\nConnected with FileServer");
			System.out.println("Typ . for exit");
			System.out.println("Please type index for a list of files or get <filename> for viewing   \n");
			
			BufferedWriter writeToNet = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
			BufferedReader readFromNet  = new BufferedReader(new InputStreamReader( s.getInputStream()));
			BufferedReader userInputStream = new BufferedReader(new InputStreamReader(System.in));
			String userInput;
			
			// processed user input
			while(!(userInput = userInputStream.readLine()).equals(".")){
				
				//show content of directory
				if (userInput.equals("index")){
					writeToNet.write(userInput, 0, userInput.length());
					writeToNet.newLine();writeToNet.flush();
					int flength = readFromNet.read();
					System.out.println(flength + " Dateien");
					for (int t = 0; t<flength; t ++){
						System.out.println("Echo: " + "\"" + readFromNet.readLine() + "\"");
						}}
				//show content of file
				else if (userInput.startsWith("get")){
					userInput.trim();
					writeToNet.write(userInput, 0, userInput.length());
					writeToNet.newLine();writeToNet.flush();
					System.out.println("Echo: " + "\"" + readFromNet.readLine() + "\"");
					int flength = readFromNet.read(); //unfortunately, doesn't work
					
					// certainly, it also doesn't work
					for (int t = 0; t<flength;t ++) {
						System.out.println("Echo: " + "\"" + readFromNet.readLine() + "\"");
				          
						
						}}
				else {System.out.println("unknown command");}
				
			}
			
			// close connection
			readFromNet.close();
			writeToNet.close();
			userInputStream.close();
			s.close();
		
		}
		catch(UnknownHostException uhe){
			System.err.println("unknown host: " + host);
		}
		catch(IOException ioe){
			System.err.println("IOException at connection with: " + host + " on Port #" + port);
		}	
	
	}

	

	public static void main(String[] args){
		
		new FileServerClient(args);
	}
}
```


Gruß Zack


----------



## madboy (29. Dez 2010)

Was erwartest du, wann die while-Schleife aufhört? while(true) tut genau das, was es soll: durch laufen bis in alle Ewigkeit ;-)


```
while (true) {
            // count lines from the file
           String line = fileIn.readLine();
          t = t+1;
           }
```

Versuche es mal so:


```
while (fileIn.readLine() != null) {
            // count lines from the file
          t = t+1;
           }
```

das selbe noch mal 5 Zeilen weiter unten im ConnectionHandler


----------



## ARadauer (29. Dez 2010)

hast du jetzt 200 Zeilen Code gepostet, weil dein Einlesen vom File nicht funktioniert?


```
String line = null;        
        while ((line = fileIn.readLine()) != null) {
          System.out.println(line);       
        }
```
Probleme eingrenzen ist ganz wichtig beim Fehler suchen ;-)


----------



## zackwlg (29. Dez 2010)

Hallo madboy, 

erst mal Danke für die schnelle Antwort. Ich habe beide Schleifen geändert. So funktionierts:



```
BufferedReader fileIn = new BufferedReader(new FileReader(file));
               
        int t = 0;
        while (fileIn.readLine() != null) {
            // count lines from the file
          t = t+1;
           }
        
        fileIn.close();
        int k = t;    
        outgoing.write(k); // for printing on client side for (int t = 0; t<flength;t ++) ...
                
        BufferedReader fileInn = new BufferedReader(new FileReader(file));       
        for (int i = 0; i<=k;i++) {
            // send lines from the file to the client
           String line = fileInn.readLine();
           outgoing.println(line);
           }
```


Also vielen Dank für die Hilfe.

Gruß Zack


----------

