2018년 11월 1일 목요일

[Java] FTP Server Example (MinimalFtp)


MinimalFtp Home: https://github.com/Guichaguri/MinimalFTP

1. FTP Server Example
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

import com.guichaguri.minimalftp.FTPConnection;
import com.guichaguri.minimalftp.FTPServer;
import com.guichaguri.minimalftp.IFTPListener;
import com.guichaguri.minimalftp.IFileSystem;
import com.guichaguri.minimalftp.IUserAuthenticator;
import com.guichaguri.minimalftp.NativeFileSystem;

public class FtpServer implements IFTPListener {

    public static void main(String[] args) throws IOException {
        User auth = new User("user", "1234", "D:\\Temp" ); 
        FTPServer server = new FTPServer();
        server.setAuthenticator(auth);
        server.addListener(new FtpServer());
        server.listenSync(21); //server.listen(21);
        server.close();
    }
    
    @Override
    public void onConnected(FTPConnection con) {
        System.out.println("[Connected] Host: " + con.getAddress().getHostAddress());
    }

    @Override
    public void onDisconnected(FTPConnection con) {
        System.out.println("[Disconnected] Host: " + con.getAddress().getHostAddress() + ", User: " + con.getUsername());
    }
}

class User implements IUserAuthenticator {
    String username;
    String password;
    String homedir;
    public User(String user, String pw, String home) { 
        username = user; 
        password = pw; 
        homedir = home; 
    }
    @Override public boolean needsUsername(FTPConnection con) { return true; }
    @Override public boolean needsPassword(FTPConnection con, String username, InetAddress address) { return true; }
    @Override public IFileSystem<?> authenticate(FTPConnection con, InetAddress address, String user, String pw) throws AuthException {
        if( ! username.equals(user) ) {
            throw new AuthException(); 
        }
        if( ! password.equals(pw) ) { 
            throw new AuthException(); 
        }
        return new NativeFileSystem(new File(homedir));
    }
}

댓글 없음:

댓글 쓰기