使用 Socket 完成
文件输入 —服务端—输出—客户端—输出—新文件地址
服务端
public class ServerDemo {
public static void main(String[] args) {
// TODO 服务器端
int count = 0;
ServerSocket socket=null;
try {
socket = new ServerSocket(8877);
FileInputStream fileInputStream = new FileInputStream("D:\\1906\\JAVA1906\\day36\\kk.jpg");
while (true) {
if (count >= 1) {
break;
}
Socket accept = socket.accept();
System.out.println("=========客户端===" + socket.getInetAddress() + "===已接入");
// 获取客户端的输入输出流
OutputStream outputStream = accept.getOutputStream();
byte[] buf = new byte[1024];
int len=0;
while ((len=fileInputStream.read(buf))!=-1) {
outputStream.write(buf,0,len);
outputStream.flush();
}
outputStream.write("okokokokoko".getBytes());
outputStream.flush();
System.out.println("=========文件已传输成功===等待客户端接收====");
count++;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
Thread.sleep(3000);
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
客户端
public class CilentDemo {
public static void main(String[] args) {
// TODO 客户端1----想下载一张图片
Socket socket = null;
try {
socket = new Socket(InetAddress.getLocalHost(), 8877);
FileOutputStream fileOutputStream = new FileOutputStream("D:\\1906\\JAVA1906\\day36\\qwe.jpg");
// 使用socket来获取输入输出流
InputStream inputStream = socket.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
String huaString = "";
while ((len = inputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 0, len);
fileOutputStream.flush();
huaString = new String(buf, 0, len);
if (huaString.contains("okokokokoko")) {
break;
}
}
System.out.println("=========客户端=====");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (socket!=null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}