1、服务端
package ztest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务端
* @author Caro
*
*/
public class UploadServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10001);
while(true){
Socket s = ss.accept();
new Thread(new UploadTask(s)).start();
}
}
}
class UploadTask implements Runnable{
private Socket s;
public UploadTask(Socket s){
this.s = s;
}
@Override
public void run() {
String ip = s.getInetAddress().getHostAddress();
File dir = new File("d:/");
File file = new File(dir, ip + "-" + System.currentTimeMillis() + ".jpg");
try {
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] b = new byte[1024];
int len = 0;
while((len = in.read(b)) != -1){
out.write(b);
out.flush();
}
out.close();
in.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、客户端
package ztest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 客户端
* @author Caro
*
*/
public class UploadClient {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("192.168.1.101", 10001);
File file = new File("d:/abc.jpg");
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());
byte[] b = new byte[1024];
int len = 0;
while((len = in.read(b)) != -1){
out.write(b, 0, len);
out.flush();
}
out.close();
in.close();
s.close();
}
}