gpt4 book ai didi

Java、FTP服务器和客户端

转载 作者:行者123 更新时间:2023-11-30 11:44:39 26 4
gpt4 key购买 nike

<分区>

我正在尝试“编写两个 Java 程序来实现 FTP 服务器,分别对 USER 和 PASS 进行响应,每个客户端线程和线程池。”我只是想确保在上交之前一切都井井有条。这是我的源代码。我遇到的唯一麻烦是弄清楚如何处理“FTPProtocol 客户端;”我应该在拥有 thread.start 之后就销毁它吗?

FTP服务器.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协议(protocol).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;
}
}
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com