(1)tcp客户端
public class upTcpClient {
public static void main(String[] args) throws IOException {
//1.利用本地IO流绑定待上传文件
FileInputStream fis = new FileInputStream("c:\\1.jpg");
//2.创建网络IO流,绑定上传目的地及端口
Socket socket = new Socket("127.0.0.1", 8888);
//3.获取网络输出流,该流可以将文件上传到目的地
OutputStream os = socket.getOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while((len=fis.read())!=-1){//4.读取待上传文件
os.write(bytes,0,len);//5.将读取的byte上传到目的地
}
socket.shutdownOutput();//6.防阻塞,当文件上传结束后自动结束while循环
InputStream is = socket.getInputStream();//7.获取网络输入流,用于读取服务器返回信息
byte[] byte1 = new byte[1024];
is.read(byte1);//8.读取返回信息,如果信息量较大,可以使用while循环读取
System.out.println(new String(byte1));//9.打印服务器返回的消息内容
//关闭流对象
fis.close();
socket.close();
}
}
(2)服务器端
public class uploadTCPServer {
public static void main(String[] args) throws IOException {
//1.创建服务器监听端口的套接字
ServerSocket ss = new ServerSocket(8888);
//2.判断文件写入的路径是否存在,不存在则创建
File file = new File("C:\\upload");
if(!file.exists()){
file.mkdirs();
}
//3.使用死循环实现无间断监听(优化1)
while(true){
//4.判断客户端是否发送连接请求,与客户端建立连接,并获取Socket流
Socket socket = ss.accept();
//利用多线程实现服务器端并发处理上传请求(优化2)
new Thread(()->{
//5.自定义文件名称(优化3)
String fileName = "njau"+System.currentTimeMillis()+new Random().nextInt(999999)+".jpg";
//6.初始化本地IO流
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file+"\\"+fileName);//绑定输出路径及文件名称
InputStream is = socket.getInputStream();//7.获取socket中的网络输入流,与客户端socket相对应
int len=0;
byte[] bytes = new byte[1024];
while((len=is.read(bytes))!=-1){//8.利用socket中的读入流的read方法,读取上传的内容
fos.write(bytes,0,len);//9.利用本地IO流将上传内容写入到对应的文件中
}
OutputStream os = socket.getOutputStream();//10.向客户端回复消息
os.write("已收到".getBytes());
fos.close();//关闭流对象
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
//ss.close();
}
}