我有一个简单的http客户端服务器。这里客户端可以从服务器下载。从我的代码客户端可以下载文件。这基本上意味着服务器文件夹中的文件成功传输到客户端。我想要做的是在控制台中显示下载的文件。我的问题是如何修改我的代码,该代码也会在控制台中显示收到的文件。
我的服务器:
public class Fileagent extends Thread
{
Socket client;
DataInputStream din;
DataOutputStream dout;
ServerSocket soc;
PrintWriter w;
BufferedReader r;
public Fileagent(Socket soc)
{
try
{
client=soc;
din=new DataInputStream(client.getInputStream());
dout=new DataOutputStream(client.getOutputStream());
w = new PrintWriter(client.getOutputStream(), true);
r= new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
start();
} ..................
public void upload() throws Exception
{
String file=din.readUTF();
File f=new File(file);
System.out.println("\nThe client requested to download the file"+" "+f);
boolean exsists=check(f);
if (exsists==false){
System.out.println("File not found in server");
out.writeUTF("ERROR");//if not found sends an ERROR message
return;
}
else
{
dout.writeUTF("FOUND");//if found in server sends a FOUND message.
FileInputStream fin=new FileInputStream(f);
int ch;
//reads and sends the file
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
dout.writeUTF("File Receive Successfully");
}
}
public Boolean check(File file){
if(file.exists())
{
return true;
}
else
{
return false;
}
}
要下载的客户端代码:
public void download(Socket s) throws Exception{
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
String request;
System.out.print("Enter File Name :");
request=con.readLine();
dout.writeUTF(request);
String msg=din.readUTF();
if(msg.compareTo("ERROR")==0)
{
System.out.println("File not found on Server ...");
return;
}
else if(msg.compareTo("FOUND")==0)
{
System.out.println("Receiving File ...");
File f=new File(request);
String option;
boolean exsists=check(f);
if(exsists==true)
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=con.readLine();
if(Option=="N")
{
dout.flush();
return;
}
}
FileOutputStream fileout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fileout.write(ch);
}
}while(ch!=-1);
fileout.close();
System.out.println(din.readUTF());
System.out.println("success");
}
答案 0 :(得分:0)
在do while循环的客户端代码中,添加System.out.write():
do {
temp=din.readUTF();
ch=Integer.parseInt(temp);
if (ch!=-1) {
fileout.write(ch);
System.out.write(ch);
}
} while(ch!=-1);