2015-05-29 85 views
1

我做了一些不同的教程,但沒有任何工作,有人可以看到我做錯了什麼?在自己的線程上同時接受多個客戶端套接字

private volatile boolean keepRunning = true; 

public FileSharedServer() { 

} 

@Override 
public void run() { 

    try { 
     System.out.println("Binding to Port " + PORT + "..."); 
     // Bind to PORT used by clients to request a socket connection to 
     // this server. 
     ServerSocket serverSocket = new ServerSocket(PORT); 

     System.out.println("\tBound."); 
     System.out.println("Waiting for Client..."); 


     socket = serverSocket.accept(); 
     System.out.println("\tClient Connected.\n\n"); 

     if (socket.isConnected()) { 
      System.out.println("Writing to client serverId " + serverId 
        + "."); 

      // Write the serverId plus the END character to the client thru 
      // the socket 
      // outStream 

      socket.getOutputStream().write(serverId.getBytes()); 
      socket.getOutputStream().write(END); 
     } 
     while (keepRunning) { 
      System.out.println("Ready"); 
      // Receive a command form the client 
      int command = socket.getInputStream().read(); 

      // disconnect if class closes connection 
      if (command == -1) { 
       break; 
      } 
      System.out.println("Received command '" + (char) command + "'"); 

      // decide what to do. 
      switch (command) { 
      case LIST_FILES: 
       sendFileList(); 
       break; 
      case SEND_FILE: 
       sendFile(); 
       break; 
      default: 
       break; 
      } 
     } 
    } catch (IOException e) { 
     System.out.println(e.getMessage()); 
    } finally { 
     // Do not close the socket here because the readFromClient() method 
     // still needs to 
     // be called. 
     if (socket != null && !socket.isClosed()) { 
      try { 
       System.out.println("Closing socket."); 
       socket.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

/** 
* This method sends the names of all of the files in the share directory. 
* 
* @throws IOException 
*/ 
private void sendFileList() throws IOException { 
    File serverFilesDir = new File("serverFiles/"); 
    if (!serverFilesDir.exists() || serverFilesDir.isFile()) { 
     System.out.println("'serverfiles' is not an existing directory"); 
     throw new IOException("'serverfiles' directory does not exist."); 
    } 
    File[] files = serverFilesDir.listFiles(); 
    for (File file : files) { 
     socket.getOutputStream().write(file.getName().getBytes()); 
     // Even the last one must end with END and then finally with 
     // END_OF_LIST. 
     socket.getOutputStream().write(END); 
    } 
    socket.getOutputStream().write(END_OF_LIST); 
} 

/** 
* this methods sends a particular file to the client. 
* 
* @throws IOException 
*/ 
private void sendFile() throws IOException { 
    StringBuilder filename = new StringBuilder(); 
    int character = -1; 
    while ((character = socket.getInputStream().read()) > -1 
      && character != END && (char) character != END_OF_LIST) { 
     filename.append((char) character); 
    } 
    System.out.println(filename); 
    File file = new File(System.getProperty("user.dir") 
      + System.getProperty("file.separator") + "serverfiles", 
      filename.toString()); 

    String totalLength = String.valueOf(file.length()); 
    socket.getOutputStream().write(totalLength.getBytes()); 
    socket.getOutputStream().write(END); 

    FileInputStream fileInputStream = new FileInputStream(file); 
    int nbrBytesRead = 0; 
    byte[] buffer = new byte[1024 * 2]; 
    try { 
     while ((nbrBytesRead = fileInputStream.read(buffer)) > -1) { 
      socket.getOutputStream().write(buffer, 0, nbrBytesRead); 
     } 
    } finally { 
     fileInputStream.close(); 
    } 
} 

public static void main(String[] args) throws InterruptedException { 
    // Create the server which waits for a client to request a connection. 

FileSharedServer server = new FileSharedServer(); 
System.out.println("new thread"); 
Thread thread = new Thread(server); 

thread.start(); 


    } 

    }  

我是否需要另一個類或只是在主要幾行?在最底部。

它是通過WiFi網絡和所有我需要的是兩個客戶同時,以上:)

+0

難道你比「無效」更精確嗎?怎麼了 ?它崩潰了嗎?它傳遞了錯誤的價值嗎? – Aracthor

+0

它阻止其中一個客戶端,無法獲得兩個客戶端,一個崩潰或停留在阻止狀態 – franklinexpress

+1

您應該在接受連接時創建線程,以便服務器線程將立即循環回「接受」命令。不知道你做了哪些教程... – RealSkeptic

回答

3

的這裏的問題是,你只運行在服務器上的一個單獨的線程。此線程接受連接,將服務器ID寫入連接,然後從連接讀取。線程繼續從連接讀取,直到接收到-1,此時線程退出。線程從來沒有嘗試接受第二個連接; ServerSocket.accept()只被調用一次。因此,您只能處理一個客戶。

你需要的是將你的班級分成兩個單獨的班級。在第一個類中,run()方法進入一個循環,調用ServerSocket.accept(),並且每次該方法返回一個套接字,創建第二個類的實例,將其傳遞給套接字並啓動它,之後它會循環回到ServerSocket.accept()調用。

第二個類與您已經編寫的類幾乎完全相同,只是它不包含ServerSocket.accept()調用。相反,socket是一個成員變量,它在啓動之前由第一個類進行初始化。它可以完成套接字的所有處理,發送服務器ID,接收和處理命令等,就像現有的代碼一樣。

相關問題