0

我试图创建一个多线程服务器套接字。它可以发送可用文件的字符串或文件作为流。问题是 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();
    } 
}

}

4

2 回答 2

0

不要打开和关闭BufferedOutputStream bufOutStream. 而是在while循环之后直接写入ps并关闭它。

关闭 bufOutStream 就像 MadProgrammer 已经提到的那样关闭套接字。

于 2013-10-20T07:53:45.213 回答
0

对于服务器应用程序,您应该使用 ServerSocket。每次新客户端请求文件时(通过 accept() 方法),ServerSocket 都必须创建新的 Socket。然后您将字节发送到新创建的套接字并可以安全地关闭它。

于 2013-10-20T07:37:18.340 回答