1

好的,所以我已经编写了我非常简单的 JAVA ftp 服务器。我现在想在同一台机器上连接到它。我正在使用 ubuntu 11.10。我一直在尝试使用命令“ftp localhost”,但一直被拒绝连接。我一直在寻找,看来我需要安装一个ftp服务器??......

我在问这是否是我应该做的,如果是的话,我在哪里可以找到它。或者我只是没有使用 ftp 命令吗?

源代码:

FTPServer.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;


public class FTPserver
{   
public static void main(String [] args)
{
    if (args.length != 1) 
        throw new IllegalArgumentException( "Parameter(s): <Port>");

    int threadPoolSize = 10;
    int port = Integer.parseInt(args[0]); 

    final ServerSocket server;
    try 
    {
        server = new ServerSocket(port);
    } 
    catch (IOException e1) 
    {
        return;
    }

    ExecutorService exec = Executors.newFixedThreadPool(threadPoolSize);

    while (true) 
    {
        try 
        {
            Socket sock = server.accept();
            exec.submit(new FTPProtocol(sock));
        } 
        catch (IOException e)
        {
            System.err.println(e.getMessage());
            return;
        }
    }
}
}

FTP协议.java

import java.io.IOException;
import java.io.InputStream;
 import java.io.OutputStream;
import java.net.Socket;

class FTPProtocol implements Runnable
{
static String greeting = "220 Service Ready.\r\n";
static String needPassword = "331 User name ok, need password.\r\n";
static String closing = "421 Service not available, closing control connection.\r\n";
static byte[] reply220 = null;
static byte[] reply331 = null;
static byte[] reply421 = null;

    Socket sock = null;
    public FTPProtocol(Socket so)
    {
        sock = so; 
        reply220 = greeting.getBytes();
        reply331 = needPassword.getBytes();
        reply421 = closing.getBytes();
    }

    public void run()
    { 
        handleFTPClient(sock); 
    }

    void handleFTPClient(Socket sock)
    {
        InputStream is = null;
        OutputStream os = null;
        byte[] inBuffer = new byte[1024];

        try 
        {
            is = sock.getInputStream();
            os = sock.getOutputStream();
            os.write(reply220);
            int len = is.read(inBuffer);
            System.out.write(inBuffer, 0, len);
            os.write(reply331);
            len = is.read(inBuffer);
            System.out.write(inBuffer, 0, len);
            os.write(reply421);
            sock.close();
        } 
        catch (IOException e)
        {
            System.err.println(e.getMessage());
            return;
        }
    }
}
4

1 回答 1

1

在 Linux 下,除非您是 root,否则您不能使用端口 21。而是绑定到例如 2121 并使用允许您指定端口号的客户端。

于 2012-05-21T17:26:03.087 回答