我目前正在使用文件傳輸客戶端和服務器程序。我可以請求並接收一個文件,但是當我嘗試請求另一個文件時,它不起作用。它給了我一個IOException。Java客戶端和服務器
進程:客戶端提示用戶輸入名稱,發送給服務器,服務器迴應文件,服務器應該等待另一個請求,而客戶端再次提示用戶輸入名稱。
我相信我並沒有在服務器端正確「等待」。任何幫助我將朝正確方向發展的幫助將會有所幫助。
客戶端代碼:
BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));
System.out.print("What file do you want? ");
name = consoleIn.readLine();
int bytesRead;
if(!name.equals("!")) {
InputStream in = null;
OutputStream output = null;
DataInputStream serverData = null;
while(!name.equals("!")) {
//fileOut = new PrintWriter(new FileOutputStream(name));
socketOut.println(name);
socketOut.flush();
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
serverData = new DataInputStream(in);
String fileName = serverData.readUTF();
output = new FileOutputStream(fileName);
long size = serverData.readLong();
byte[] buffer = new byte[4000];
while (size > 0 && (bytesRead = serverData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
{
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
System.out.print("What file do you want? ");
name = consoleIn.readLine();
}
}
服務器代碼:
socket = serverSocket.accept();
System.out.println("Connection accepted!");
BufferedReader socketIn =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
//PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
String name;
BufferedReader fileIn;
String line;
name = socketIn.readLine();
System.out.println(name);
while((!name.equals("!")) && (!name.equals("*"))) {
File file = new File(rootDirectory, name);
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(file.getName());
dos.writeLong(bytes.length);
dos.write(bytes, 0, bytes.length);
dos.flush();
System.out.println("Sending: " + name);
os.write(bytes, 0, bytes.length);
os.flush();
name = socketIn.readLine();
System.out.println(name);
}
爲什麼fis.close()被註釋掉? –
您似乎正在關閉客戶端的連接? –
@EvanKnowles我關閉客戶端的連接,如果!標記在輸入中被檢測到。 –