文件上传的客户端:
1.创建客户端,连接服务端
2.创建文件输入流
3.获取Socket输出流
4.读取文件数据
5.写入到Socket输出流
6.循环读写
public class UploadClient {
public static void main(String[] args) throws IOException {
System.out.println("客户端启动了");
Socket socket = new Socket("127.0.0.1",10086);
FileInputStream fis = new FileInputStream("E:\\software\\IDEA\\JAVASE_mix_01_14\\day08_课堂代码\\捕获.PNG");
OutputStream out = socket.getOutputStream();
byte[] buf = new byte[1024];
int len;
while((len=fis.read())!=-1){
out.write(buf,0,len);
}
socket.shutdownOutput();
InputStream in = socket.getInputStream();
byte[] buf2 = new byte[1024];
int len2 = in.read(buf2);
System.out.println("客户端收到: " + new String(buf2,0,len2));
out.close();
fis.close();
socket.close();
}
}
文件上传的务端流程:
1.创建服务端,绑定端口
2.同意客户端的请求
3.创建文件输出流
4.获取Socket的输入流
5.使用Socket的输入流读取数据
6.使用文件输出流写数据到文件
7.循环读写
8.获取Socket的输出流写数据给客户端
9.关闭流
public class UploadServer {
public static void main(String[] args) throws IOException {
System.out.println("服务端启动了。。。");
ServerSocket ss = new ServerSocket(10086);
Socket s = ss.accept();
System.out.println(s.getInetAddress());
Random ran = new Random();
int i = ran.nextInt(999999999);
String fileName = "E:\\software\\IDEA\\JAVASE_mix_01_14\\day08_课堂代码\\Test09\\p.png"+System.currentTimeMillis()+"_"+"p.png";
FileOutputStream fos= new FileOutputStream(fileName);
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf))!=-1){
fos.write(buf,0,len);
}
System.out.println("文件上传结束。。。");
OutputStream out = s.getOutputStream();
out.write("上传成功。。。".getBytes());
out.close();
in.close();
fos.close();
s.close();
ss.close();
}
}