通过套接字将文件从客户端发送到服务器

时间:2017-05-23 06:53:15

标签: java file sockets server client

我正在尝试编写一个程序,将文件从客户端上传到服务器。我认为我现在遇到的问题是服务器不等待客户端开始发送。非常感谢任何关于出错的指示。该程序有很多,包括一个GUI,但我会尝试只包括相关的代码。

服务器

private InputStream in = null;
private OutputStream out = null;
private Socket socket;

private void startServer() {
    try {
        while (true) {
            ServerSocket server = new ServerSocket(port);
            System.out.println("Server started and listening on port " + port);
            socket = server.accept();
            System.out.println("Client connect from " + socket.getRemoteSocketAddress());
            in = new FileInputStream("File10.txt");
            out = socket.getOutputStream();

            while (in.read() >= 0) {
                receiveFile("File10.txt");
            }
        }
    } catch (Exception e) {
        System.out.println("File read failed");
    }

}

private void receiveFile(String name) {
    byte[] bytes = new byte[16 * 1024];
    File file = new File(name);
    int count = 0;

    try {
        while ((count = in.read(bytes)) > 0) {
            out.write(bytes, 0, count);
            System.out.println("File read");
        }
    } catch (Exception e) {
        System.out.println("Could not read file");
    }
}

客户端

Queue<File> fileQueue = new ArrayDeque<File>();

private void startClient() {
    try {
        socket = new Socket(serverAddress, port);
        System.out.println("Connected to server at " + socket.getRemoteSocketAddress());

    } catch (Exception ex) {
        System.out.println("Could not connect to server");
    }
    try {
        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        pw = new PrintWriter(socket.getOutputStream(), true);
        System.out.println("Reader/writer started");
    } catch (Exception e) {
        System.out.println("Reader/writer failed to start");
    }
}

private void sendFiles() {
    byte[] bytes = new byte[(int) fileQueue.peek().length()];
    int counter;

    try {
        fin = new FileInputStream(fileQueue.peek());
        bin = new BufferedInputStream(fin);
    } catch (Exception e) {
        System.out.println("Could not start Reader");
    }
    try {
        out = socket.getOutputStream();
        out.write(bytes, 0, bytes.length);
        System.out.println("Sending file ... ");
    } catch (Exception e) {
        System.out.println("Could not send file");
    }
 }

最终,程序将从队列中读取文件并将其上传到服务器。我只用了8个星期的时间学习Java,而且我可能会选择构建什么来有点野心勃勃。

0 个答案:

没有答案