如何使用Socket编程将文件列表从服务器发送到客户端。我使用过DataOutputStream和PrintWriter,它们都只向Client返回一个文件名。我知道'\ n'中存在一些问题。但无法解决它。等待专家建议......谢谢。
客户端
switch (choice) {
.......
case 2: // for viewing files in the client's directory
Socket mysocket = new Socket("localhost", 6103);
String user_name = username;
DataOutputStream outToServer2= new DataOutputStream(mysocket.getOutputStream());
outToServer2.writeBytes(user_name + '\n');
BufferedReader inFromServer2 = new BufferedReader(newInputStreamReader(mysocket.getInputStream()));
String list = inFromServer2.readLine();
System.out.println("FROM SERVER - LIST OF FILES:" + list);
break;
}
.......
服务器
import java.io.*;
import java.net.*;
class DirList
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6103);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(),true);
clientSentence = inFromClient.readLine();
System.out.println("Received view files request from user: " + clientSentence);
String path = "/home/user/Files/";
String userdir = path + clientSentence;
String text="";
String capitalizedSentence1;
File f = new File(userdir);
File[] listOfFiles = f.listFiles();
for (int j = 0; j < listOfFiles.length; j++) {
if (listOfFiles[j].isFile()) {
text = listOfFiles[j].getName();
outToClient.println(text);
System.out.print(text+' ');
}
}
}
}
}
答案 0 :(得分:3)
您需要刷新服务器的输出:
outToClient.flush();
此外,在您的客户端中,您需要将读取放在循环中以消耗所有输出:
String line = null;
while ((line = inFromServer2.readLine()) != null) {
System.out.println(line);
}
答案 1 :(得分:0)
尝试使用“\ r \ n”。它可能会解决您的问题。