Java多线程服务器套接字

时间:2013-10-20 07:16:27

标签: java multithreading sockets

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

}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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