我正在尝试“编写两个实现 FTP 服务器的 Java 程序,分别响应 USER 和 PASS,每个客户端线程和线程池。” 我只是想在上交之前确保一切都井井有条。这是我的源代码。我遇到的唯一麻烦是弄清楚如何处理“FTPProtocol 客户端”;我应该在拥有 thread.start 后将其销毁吗?
FTPServer.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
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;
}
for (int i = 0; i < threadPoolSize; i++)
{
Thread thread = new Thread()
{
public void run()
{
while (true)
{
try
{
Socket sock = server.accept();
FTPProtocol client = new FTPProtocol(sock);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return;
}
}
}
};
thread.start();
}
}
}
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;
}
}
}