我正在使用浏览器通过简单地输入地址 127.0.0.1:1501/filename.png 向服务器发送获取请求。目的是从服务器下载文件。服务器成功接收请求并加载所选文件,它还进入while循环并多次执行打印方法,这意味着正在发送某些东西,但在“网络”选项卡中的谷歌浏览器上检查我只得到filename.png失败我不明白为什么这段代码似乎不起作用。print 是一个简单地调用 System.out.println() 方法的方法
public class MainClassServer {
public static void main(String[] args){
// TODO Auto-generated method stub
ServerSocket server = null;
try {
server = new ServerSocket();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
server.bind(new InetSocketAddress("127.0.0.1", 1501));
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true) {
String message;
Socket client = null;
print("Waiting for client...");
try{
client = server.accept();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
BufferedReader reader = null;
DataOutputStream writer = null;
try {
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
message = reader.readLine();
if(message!=null) {
//I get the correct filename with string manipulation
// I correctly access the file in fact it exist
File file = new File(path);
if(file.exists()) {
byte[] bytes = new byte[1024];
InputStream in = new FileInputStream(path);
int count;
while ((count = in.read(bytes)) > 0) {
//the program print some bytes so it writes something to someone
print("Sending " + count + " bytes");
writer.write(bytes, 0, count);
}
writer.flush();
}else {
print("File does not exsist.");
}
writer.close();
reader.close();
server.close();
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}