描述:这是基于TCP套接字的FTP程序的FTPClient.java类。我的教授说我的程序很好,除了FTPClient.java类中的run()方法。他说我的run()方法正在阅读所有内容而不仅仅是阅读特定的命令。
问题:我应该在此方法中使用String [] output = something.split(“”)吗?你能帮我找出这种方法的正确代码吗?
谢谢!
package ftp.server;
import java.net.*;
import java.io.*;
public class FTPClient
{
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
private BufferedReader keyboard = null;
final private String EXIT_CMD = "exit";
final private String PUT_CMD = "put";
final private String GET_CMD = "get";
public FTPClient(Socket socket) throws IOException
{
this.socket = socket;
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
keyboard = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
}
public void sendFile(String fileName) throws IOException
{
File file = new File(fileName);
if(!file.exists())
{
output.writeUTF("File " + fileName + " does not exist");
}
else
{
output.writeUTF(fileName);
FileInputStream inFile =
new FileInputStream(file);
int ch;
do
{
ch = inFile.read();
output.writeUTF(String.valueOf(ch));
}while(ch != -1);
inFile.close();
}
}
public void receiveFile(String fileName) throws IOException
{
output.writeUTF(fileName);
String msg = input.readUTF();
if(msg.equals("NOT_FOUND"))
{
output.writeUTF("No file in server");
}
else if(msg.equals("READY"))
{
File file = new File(fileName);
FileOutputStream outFile =
new FileOutputStream(file);
int ch;
String line;
do
{
line = input.readUTF();
ch = Integer.parseInt(line);
if(ch != -1)
{
outFile.write(ch);
}
}while(ch != -1);
outFile.close();
}
}
public void run() throws IOException
{
while(true)
{
System.out.println("ftp>");
String cmd = keyboard.readLine();
if(cmd.equals(PUT_CMD))
{
output.writeUTF(PUT_CMD);
sendFile("novel.dat");
}
if(cmd.equals(GET_CMD))
{
output.writeUTF(GET_CMD);
receiveFile("novel.dat");
}
if(cmd.equals(EXIT_CMD))
{
output.writeUTF(EXIT_CMD);
}
}
}
public static void main(String[] args) throws Exception
{
//check parameters
if(args.length != 2)
{
System.out.println("Usage: java FTPClient <host> <port>");
return;
}
//create socket
String host = args[0];
int port = Integer.parseInt(args[1]);
Socket socket = new Socket(host, port);
//run ftp client
FTPClient client = new FTPClient(socket);
client.run();
}
}
答案 0 :(得分:1)
这是我修复run方法所需要做的事情:
public void run() throws IOException
{
while(true)
{
System.out.print("ftp>");
String cmd = keyboard.readLine();
if(cmd.equals(EXIT_CMD))
{
output.writeUTF(EXIT_CMD);
System.exit(0);
}
String[] tokens = cmd.split(" ");
cmd = tokens[0];
String fileName = tokens[1];
if(cmd.equals(PUT_CMD))
{
output.writeUTF(PUT_CMD);
sendFile(fileName);
}
else if(cmd.equals(GET_CMD))
{
output.writeUTF(GET_CMD);
receiveFile(fileName);
}
}
}