TCP之文件上传与下载
2021-02-16 22:18
标签:输出流 输出 address ati fileinput 输入 文件上传 ddr except 执行结果:服务端接受到客户端发送的文件 TCP之文件上传与下载 标签:输出流 输出 address ati fileinput 输入 文件上传 ddr except 原文地址:https://www.cnblogs.com/Kuris101/p/12964345.htmlTCP文件上传下载
客户端
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TCPClientFile {
public static void main(String[] args) throws Exception{
//1.创建socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
//2.创建输出流
OutputStream os = socket.getOutputStream();
//3.读取文件
FileInputStream fileInputStream = new FileInputStream(new File("D:\\Code\\JavaStudy\\src\\zhengjianzhao.jpg"));
//4.写出文件
byte[] buffer = new byte[1024];
int len;
while((len=fileInputStream.read(buffer))!=-1){
os.write(buffer,0,len);
}
//5.关闭资源
fileInputStream.close();
os.close();
socket.close();
}
}
服务端
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.File;
public class TCPServerFile {
public static void main(String[] args) throws Exception{
//1.创建服务
ServerSocket serverSocket = new ServerSocket(9000);
//2.等待连接
Socket socket = serverSocket.accept();
//3.获取输入流
InputStream is = socket.getInputStream();
//4.文件输出
FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//5.关闭资源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
上一篇:flask之模板呈现html文件
下一篇:js练习时钟效果