我试图创建一个多线程服务器套接字。它可以发送可用文件的字符串或文件作为流。问题是 else 块,它将请求的文件作为流发送,只工作一次。我的代码中的问题在哪里,为什么它只回复一次?
public class ServerThread extends Thread {
Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
String message = null;
PrintStream ps = null;
String string = null;
File file = null;
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
while ((message = bufferedreader.readLine()) != null) {
if (message.equals("list")) {
ps.println(Arrays.toString(getServerFiles()));
} else {
message = "FilesServer\\" + message;
file = new File(message);
//JOptionPane.showConfirmDialog(null, message);
if (file.exists()) {
BufferedInputStream bfInStream =
new BufferedInputStream(new FileInputStream(message));
BufferedOutputStream bufOutStream =
new BufferedOutputStream(socket.getOutputStream());
byte[] buffer = new byte[1024];
int read = 0;
while ((read = bfInStream.read(buffer)) != -1) {
bufOutStream.write(buffer, 0, read);
bufOutStream.flush();
}
bufOutStream.close();
System.out.println("File transfered");
}
}
}
} catch (Exception e) {
//JOptionPane.showConfirmDialog(null, e.getMessage());
}
}
private static String[] getServerFiles() {
String result[];
File folder = new File("FilesServer\\");
File[] listOfFiles = folder.listFiles();
result = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
result[i] = listOfFiles[i].getName();
}
}
return result;
}
}
上面的类是从这个类中调用的:
public class Server {
private int defaultPort = 8088;
public static void main(String[] args) throws IOException {
new Server().InitServer();
}
private void InitServer() throws IOException{
ServerSocket serversocket = new ServerSocket(8081);
while(true){
Socket socket = serversocket.accept();
new ServerThread(socket).start();
}
}
}