服务器从客户端接受文件名

时间:2012-12-19 16:45:14

标签: java

服务器部分发送到客户端目录中的可用文件列表,客户端选择其中一个,然后从客户端请求发送到服务器,然后服务器发送文件到客户端。我有服务器问题,我不知道如何接受客户端请求的文件名,也许有人有想法?

服务器部分:

import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
    ServerSocket ss = null;
    try {
        ss = new ServerSocket(9999);
    } catch(IOException e) {
        e.getStackTrace();
    }
    while(true) {
        try {
            Socket s = ss.accept();
            System.out.println("Connection: " +s);
            PrintWriter out = new PrintWriter(s.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String fileName = getFileName("E://share//");
            //sending available files names to client
            out.println(fileName);
            out.close();
            //System.out.println("File requested from client:");
            //String file = in.readLine();
            //System.out.println(file);
            s.close();
        } catch(IOException e) {
            e.printStackTrace();
        } 
        //ss.close();
    }
}//methode which get file names from directory
public static String getFileName(String folderName) {
    File folder = new File(folderName);
    File[] listOfFiles = folder.listFiles();
    StringBuffer sb = new StringBuffer();
    for(int i=0; i<listOfFiles.length; i++) {
       //System.out.println(listOfFiles[i].getName());
       sb.append(listOfFiles[i].getName()+"\n");
       }
    return sb.toString();
}
}

客户端部分:

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
    Socket s = new Socket(InetAddress.getLocalHost(),9999);
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    //for gettin file name from available
    PrintWriter out = new PrintWriter(s.getOutputStream(), true);
    BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
    //output from server, available file list
    String fileNames;
    while((fileNames = br.readLine()) != null) {
        System.out.println(fileNames);
    }
    br.close();
 //imputing file name which have to be send from server to client
    System.out.println("Which file do you want to send:");
    String fileName = sin.readLine();
    out.println(fileName);
    out.close();
    s.close();
} catch(IOException e) {
    e.printStackTrace();
}

}
}

0 个答案:

没有答案