客户端:
public class Test2_UpdateClient {
public static void main(String[] args) throws Exception {
//获取一个文件
File file = getFile();
//文件名称传递到服务端
Socket socket = new Socket("127.0.0.1",12345);
OutputStream out = socket.getOutputStream();
PrintStream ps = new PrintStream(out);
ps.println(file.getName());
//获取服务端返回的数据
InputStream in = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String result = br.readLine();
//如果存在,提示该文件已经存在
if("存在".equals(result)){
System.out.println("服务端已经存在该文件,请勿重复上传");
socket.close();
return;
}
//如果不存在
//拿到二进制输入流
FileInputStream fin = new FileInputStream(file);
byte[] arr = new byte[1024];
int len = 0;
while((len=fin.read(arr))!=-1){
//传递给服务端
out.write(arr, 0, len);
}
fin.close();
//socket关闭
socket.close();
}
private static File getFile() {
//键盘输入流
Scanner scanner = new Scanner(System.in);
System.out.println("输入文件路径");
while(true){
//获取输入的文件路径
String path = scanner.nextLine();
File file = new File(path);
if(!file.exists()){
System.out.println("该路径不是一个文件路径,请重新输入");
}else if(file.isDirectory()){
System.out.println("该路径不是一个文件,请重新输入");
}else{
return file;
}
}
}
}
服务端:
public class Test2_UpdateServer {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(12345);
System.out.println("服务端启动");
File dir = new File("upload");
if(!dir.exists()){
dir.mkdir();
}
while(true){
Socket socket = server.accept();
new Thread(){
public void run() {
try {
InputStream in = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
PrintStream ps = new PrintStream(socket.getOutputStream());
String line = br.readLine();
//该处如果再次读取,会报错 Connection reset
//br.readLine();
File file = new File(dir,line);
if(file.exists()){
ps.println("存在");
socket.close();
return;
}
//服务端不存在客户端传递文件名称
ps.println("不存在");
int read2 = in.read();
System.out.println("后面长度:"+read2);
//拿到服务端的二进制流
FileOutputStream fout = new FileOutputStream(file);
byte[] arr = new byte[1024];
int len = -1;
while((len=in.read(arr))!=-1){
fout.write(arr,0, len);
}
fout.close();
//关闭socket
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
}
}