2014-02-19 4 views
0

am делает простую ftp-клиент/серверную программу, которая по команде из списка клиентов перечисляет файлы, сообщает текущему каталогу, загружает файлы.Socket получает Closed после 1-й команды

Я хочу создать сервер, который может подключаться к нескольким клиентам и способен обрабатывать сразу несколько команд. Я использовал потоки, но мой код дает следующую ошибку после выполнения 1-й команды.

socket closed 
at java.net.SocketInputStream.socketRead0(Native Method) 
at java.net.SocketInputStream.read(Unknown Source) 
at java.net.SocketInputStream.read(Unknown Source) 
at java.io.DataInputStream.read(Unknown Source) 
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source) 
at sun.nio.cs.StreamDecoder.implRead(Unknown Source) 
at sun.nio.cs.StreamDecoder.read(Unknown Source) 
at java.io.InputStreamReader.read(Unknown Source) 
at java.io.BufferedReader.fill(Unknown Source) 
at java.io.BufferedReader.readLine(Unknown Source) 
at java.io.BufferedReader.readLine(Unknown Source) 
at Myserver$Connecthandle.run(Myserver.java:123) 
at Myserver.main(Myserver.java:35) 
java.net.SocketException: socket closed 

Вот мой код сервера:

public class Myserver { 
static final int PortNumber = 120; 
static ServerSocket MyService; 
static Socket clientSocket = null; 
/** 
* @param args 
* @throws IOException 
*/ 
public static void main(String[] args) throws IOException { 
    File directory; 
    directory = new File(System.getProperty("user.dir")); 
    try { 
      MyService = new ServerSocket(PortNumber); 
      String cd = directory.toString(); 
      System.out.println(cd); 
      System.out.println("Listening on " + PortNumber); 
      while(true) { 
      clientSocket = MyService.accept(); 
      Connecthandle a = new Connecthandle(clientSocket, directory); 
      a.start(); 
      } 
    } 
    catch (IOException e) { 
    System.out.println(e); 
    } 
} 

    static class Connecthandle extends Thread { 
     File Directory; 
     Socket clientsocket; 
     PrintWriter outgoing; 

     // Constructor for class 
     Connecthandle(Socket clients, File dir) { 
      clientsocket = clients; 
      Directory = dir; 
     } 

     // Works Fine 
     void listfiles() throws IOException { 
      String []Listfile = Directory.list(); 
      String send = ""; 
      for (int j = 0; j < Listfile.length; j++) { 
       send = send + Listfile[j] + ","; 
      } 
      DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream()); 
      GoingOut.writeBytes(send); 
      GoingOut.flush(); 
      // GoingOut.close(); 
     } 
     // Works Fine 
     void currentdirectory() throws IOException { 
      String cd = Directory.toString(); 
      String cdd = "resp," + cd; 
      System.out.println(cdd); 
      DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream()); 
      GoingOut.writeBytes(cdd); 
      GoingOut.flush(); 
      GoingOut.close(); 
     } 

     // Works fine 
     void sendfiles(String fileName) { 
      try { 
      File nfile = new File(fileName); 
      DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream()); 
      if ((! nfile.exists()) || nfile.isDirectory()) { 
       GoingOut.writeBytes("file not present"); 
      } else { 
      BufferedReader br = new BufferedReader(new FileReader(nfile)); 
      int coun = 0; 
      String lin; 
      while ((lin = br.readLine()) != null) { 
       coun++; 
      } 
      GoingOut.writeBytes("resp," + fileName + "," + String.valueOf(coun) + "\n"); 
      @SuppressWarnings("resource") 
      BufferedReader sr = new BufferedReader(new FileReader(nfile)); 
      String line; 
      while ((line = sr.readLine()) != null) { 
       GoingOut.writeBytes(line+"\n"); 
       GoingOut.flush(); 
      } 
      GoingOut.close(); 
      br.close(); 
      } 
      } catch (IOException e) { 
       System.out.println("Unable to send!"); 
      } 
     } 

     public void start() { 
      DataInputStream comingin = null; 
      try { 
       comingin = new DataInputStream(clientsocket.getInputStream()); 
      } catch (IOException e2) { 
       e2.printStackTrace(); 
      } 
      InputStreamReader isr = null; 
      try { 
       isr = new InputStreamReader(comingin, "UTF-8"); 
      } catch (UnsupportedEncodingException e1) { 
       e1.printStackTrace(); 
      } 
      BufferedReader br = new BufferedReader(isr); 
      while (true) { 
      try { 
      String message = br.readLine(); 
      if (message.contains("pwd")) { 
       currentdirectory(); 
      } else if (message.contains("list")) { 
       listfiles(); 
      } else if (message.contains("get")) { 
       String fileName = new String(message.substring(8, message.length())); 
       sendfiles(fileName); 
      } else if (message.contains("exit")) { 
       System.exit(0); 
      } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } finally { 
       try { 
        clientsocket.close(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
      } 
     } 
    } 

} Я переехал все методы в начале(), так что я только нужно объявить DataOutputStream один раз, но теперь она дает NullPointerException всякий раз, когда я использую Outgoing.writeBytes

Обновлено:

static class Connecthandle extends Thread { 
     File Directory; 
     Socket clientsocket; 
     PrintWriter outgoing; 

     // Constructor for class 
     Connecthandle(Socket clients, File dir) { 
      clientsocket = clients; 
      Directory = dir; 
     } 

     public void run() { 
      DataInputStream comingin = null; 
      try { 
       comingin = new DataInputStream(clientsocket.getInputStream()); 
      } catch (IOException e2) { 
       e2.printStackTrace(); 
      } 
      InputStreamReader isr = null; 
      try { 
       isr = new InputStreamReader(comingin, "UTF-8"); 
      } catch (UnsupportedEncodingException e1) { 
       e1.printStackTrace(); 
      } 
      BufferedReader br = new BufferedReader(isr); 
      while (true) { 
      try { 
      String message = br.readLine(); 
      if (message.contains("pwd")) { 
       String cd = Directory.toString(); 
       String cdd = "resp," + cd; 
       System.out.println(cdd); 
       DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream()); 
       GoingOut.writeBytes(cdd); 
       GoingOut.flush(); 
      } else if (message.contains("list")) { 
       String []Listfile = Directory.list(); 
       String send = ""; 
       for (int j = 0; j < Listfile.length; j++) { 
        send = send + Listfile[j] + ","; 
       } 
       DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream()); 
       GoingOut.writeBytes(send); 
       GoingOut.flush(); 
      } else if (message.contains("get")) { 
       String fileName = new String(message.substring(8, message.length())); 
       try { 
        File nfile = new File(fileName); 
        DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream()); 
        if ((! nfile.exists()) || nfile.isDirectory()) { 
         GoingOut.writeBytes("file not present"); 
        } else { 
        BufferedReader wr = new BufferedReader(new FileReader(nfile)); 
        int coun = 0; 
        String lin; 
        while ((lin = wr.readLine()) != null) { 
         coun++; 
        } 
        GoingOut.writeBytes("resp," + fileName + "," + String.valueOf(coun) + "\n"); 
        @SuppressWarnings("resource") 
        BufferedReader sr = new BufferedReader(new FileReader(nfile)); 
        String line; 
        while ((line = sr.readLine()) != null) { 
         GoingOut.writeBytes(line+"\n"); 
         GoingOut.flush(); 
        } 
        GoingOut.close(); 
        br.close(); 
      } 
       } catch (IOException e) { 
        System.out.println("Unable to send!"); 
       } 
      } else if (message.contains("exit")) { 
       System.exit(0); 
      } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } finally { 
       try { 
        clientsocket.close(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
      } 
     } 
    } 
} 
+0

Вы не закрываете сокет после первой команды? –

+0

Не могли бы вы рассказать мне, где? и как я могу избежать этого? – user3293371

+1

'clientsocket.close();' в вашем блоке finally ... Также я не на 100%, но закрытие потока, которое вы получаете из сокета, может также закрыть сокет ... –

ответ

0

Закрытие тыс e входной поток или выходной поток сокета закрывает другой поток и сокет. Я не понимаю, почему вам нужно закрыть что-либо здесь до тех пор, пока клиент не отключится или вы не выберете его.

Смежные вопросы