编写代码
1,服务端接收文件 TcpServerDemo02
package com.xiang.lesson02;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
//服务端接收文件
public class TcpServerDemo02 {
public static void main(String[] args) throws Exception {
// 1,创建一个端口 创建一个服务
ServerSocket socket = new ServerSocket(9000);
// 2,监听客户端的连接
Socket accept = socket.accept();
// 3,获取输入流
InputStream is = accept.getInputStream();
// 4,文件输出
FileOutputStream fos = new FileOutputStream(new File("res"));
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
// 通知客户端 ,我接收完成
OutputStream os = accept.getOutputStream();
os.write("我这边接收完毕了,你可以断开了".getBytes(StandardCharsets.UTF_8));
// 关闭资源
fos.close();
is.close();
accept.close();
socket.close();
}
}
2,客户端读取文件 TcpClientDemo02
package com.xiang.lesson02;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端读取文件;
public class TcpClientDemo02 {
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 fis = new FileInputStream(new File("javaee.txt"));
// 4,写出文件
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
// 通知服务器,我已经结束 了
socket.shutdownOutput(); //我已传输完了
// 确定服务器接收完毕,才断开连接
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while ((len2=inputStream.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
// 5,关闭资源
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
3,运行结果