2

简要说明 :

我的应用程序将文件从服务器端发送到客户端,客户端选择文件名和扩展名,但是,为了让客户端看到文件列表,我编写了一个方法来列出可用的文件服务器。

虽然该方法有效,但我需要将文件名发送给客户端并将它们插入并在JPanel那里列出它们,以便用户可以选择他想要的文件。

这是我在服务器端的方法:

 public static void listfile() {

 String path = "C:/SAVE"; 

  String files;
  File folder = new File(path);
  File[] listOfFiles = folder.listFiles(); 

  for (int i = 0; i < listOfFiles.length; i++) 
  {

   if (listOfFiles[i].isFile()) 
   {
   files = listOfFiles[i].getName();
   System.out.println(files);
      }
  }
    }

如何修改它以便在调用时将文件列表发送给客户端。

4

1 回答 1

1

如果您使用 tcp 连接,您的服务器可以实现一个名为“listFiles”的命令。当它接收到这个命令时,它应该向客户端发送文件列表。

客户端应该连接到服务器,发送命令“listFiles”,读入服务器发送的文件列表并将其显示在其 JPanel 上。

假设您有一个采用以下模式的简单单线程服务器:

class Server
{
    public void run()
    {
        ServerSocket server = new ServerSocket(<portno>);

        Socket socket = server.accept();

        InputStream in = socket.getInputStream(); // for reading the command

        OutputStream out = socket.getOutputStream(); // for writing out the list

        // Now read the argument from in, say the result is in variable "cmd"

        if("listFiles".equals(cmd))
        {
            // invoke your list files logic, and instead of writing to the console
            // write it to out
        }
    }
}

您的客户应遵循以下模式:

class Client
{
    public void getList()
    {
        Socket client = new Socket(<portno>);
        InputStream in = client.getInputStream(); // to read in the file list
        OutputStream out = client.getOutputStream(); // to send the listFiles command

        // Write the  listFiles command to out

        // Read in the list of files from in

        // Update your JPanel with the list
    }
}

我省略了从/到套接字的实际读取和写入,但你会明白的。

于 2013-01-14T14:26:46.587 回答