业务分为服务端和客户端
客户端
1.创建一个socket连接(要知道服务端的ip地址和端口号)
2.创建一个文件输出流
3.读取文件把文件转为流
4.创建一个byte数组来储存流文件
5.把文件写入文件输出流
6.告诉服务器已经上传完毕
7.等待服务器响应
package com.shxp.yuan.tcp;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception{
/*1.创建一个socket连接*/
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9999);
/*2.创建一个输出流*/
OutputStream os = socket.getOutputStream();
/*3.开始读取文件*/
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\cheng\\Desktop\\全套SpringBoot入门到项目实战课程.pdf");
/*4.开始写出文件*/
byte[] buffer = new byte[1024];
int len;
while ((len=fileInputStream.read(buffer))!=-1){
os.write(buffer,0,len);
}
socket.shutdownOutput();
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[2014];
int len2;
while ((len2=is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println("===="+baos.toString());
/*5.关闭资源*/
baos.close();
fileInputStream.close();
os.close();
}
}
服务端
1.创建一个服务器端连接
2.监听客户端的状态
3.获取输入流
4.把文件写入到指定我呢见
5.告诉客户端已经接受完毕
package com.shxp.yuan.tcp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.InflaterOutputStream;
public class TcpServiceDemo02 {
public static void main(String[] args) throws Exception{
/*1.创建一个服务端socket*/
ServerSocket serverSocket = new ServerSocket(9999);
/*2.监听客户端连接*/
Socket socket = serverSocket.accept();
/*3.获取输入流*/
InputStream stream = socket.getInputStream();
/*4.开始文件输出*/
FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\ftp\\cheng\\haha.pdf"));
byte[] buffer = new byte[1024];
int len;
while ((len=stream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,len);
}
/*告诉客户端已经传输完毕*/
OutputStream os = socket.getOutputStream();
os.write("我已经完事了".getBytes());
}
}