具体需求是这样的:
server1有个文件x.war,server2发起一个http请求到服务器端server1下载文件x.war,具体的请求是http://server1/downloadservlet,然后这个请求会返回文件x.war,server2接到返回结果后直接把把该文件保存到目录c:/bak下。
在服务端起个socket监听,客户端链接,然后下载
以下例子是客户端将服务器上存放在d:\mp4\test.mp4保存到本地d:\test2.dat
但服务器只能处理单个请求,可以自己试试将它改成多线程支持,练习下下
package socket;
import java.io.*;
import java.net.*;
public class DataServer {
/**
* @param args
*/
public static final int SERVICE_PORT=1500;
public static final int DATA_SIZE=1024*30;
public static void main(String[] args) {
// TODO Auto-generated method stub
String filePath="d:"+File.separator+"MP4"+File.separator+"test.MP4";
File fileOut=new File(filePath);
if(!fileOut.exists()){
System.out.println("File Not Found");
return;
}
try{
ServerSocket server = new ServerSocket(SERVICE_PORT);
System.out.println("Service started");
for(;;){
Socket nextClient = server.accept();
System.out.println("Received request from " + nextClient.getInetAddress()+ ":"+ nextClient.getPort());
FileInputStream fis=new FileInputStream(fileOut);
OutputStream out =nextClient.getOutputStream();
PrintStream fileOutS = new PrintStream(out);
fileOutS.print(filePath+"\r\n");
byte[] bs = new byte[DATA_SIZE];
int length;
System.out.println("Sending data...");
while ( (length=fis.read(bs)) != -1){
out.write(bs,0,length);
bs = new byte[DATA_SIZE];
Thread.sleep(500);
}
System.out.println("Data sending completed");
fileOutS.close();
fis.close();
out.flush();
out.close();
nextClient.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
客户端
package socket;
import java.net.*;
import java.io.*;
public class DataClient {
public static final int SERVICE_PORT = 1500;
public static final int DATA_SIZE = 1024*60;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String hostName="192.168.10.201";
String filePath="D:"+File.separatorChar+"test2.dat";
try{
Socket client = new Socket(hostName,SERVICE_PORT);
System.out.println("Connection established");
System.out.println(client.getRemoteSocketAddress());
client.setSoTimeout(2000);
File file=new File(filePath);
if(file.exists()){
file.delete();
System.out.println("Create new file");
}
InputStream in = client.getInputStream();
BufferedReader readerFile = new BufferedReader(
new InputStreamReader(in));
DataInputStream reader = new DataInputStream(in);
FileOutputStream fos = new FileOutputStream(file);
String filename=readerFile.readLine();
System.out.println(filename);
byte[] bs = new byte[DATA_SIZE];
int length;
System.out.println("Data receiving started");
while( (length=reader.read(bs)) != -1){
fos.write(bs,0,length);
bs = new byte[DATA_SIZE];
Thread.sleep(200);
}
System.out.println("Receiving completed");
readerFile.close();
reader.close();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}