服务端
监听需要while无限循环,try-catch需写到循环内,这样在抛出异常时,只会断掉本次会话,while循环(监听)仍会继续,否则监听会断掉,需重新创建serverSocket。
具体细节看代码注释
package com.utils.socketFile;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class ServeSocket implements Runnable {
//监听端口
private static int port = 1128;
//文件大小
private static int fileSize = 500*1024;//500K
//文件路径
private static String filePath = "C:\\Users\\Desktop\\";
@SuppressWarnings("InfiniteLoopStatement")
public void run() {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
DataInputStream dis = null;
DataOutputStream dos = null;
//获取文件名缓冲区
byte[] temName = new byte[1024];
int lenName;
String fileName = "";
//获取文件缓冲区
byte[] temFile = new byte[8192];
int lenFile;
//创建服务端
try {
System.out.println("服务端创建");
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
//监听
while(true){
try{
socket = serverSocket.accept();//开始监听
//接收客户端上传的文件名
is = socket.getInputStream();
while ((lenName = is.read(temName)) != -1) {
fileName = new String(temName, 0, lenName);
System.out.println("服务器接受文件名:" + fileName);
}
dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
//判断文件 F00文件存在 F01文件过大 F02文件不存在 F03其他异常
File file = new File(filePath + fileName);
if (file.exists() && file.isFile()){
if (file.length() > fileSize){
//响应结果给客户端
dos.write("F01".getBytes(StandardCharsets.UTF_8));
System.out.println("文件超过最大限制");
continue;
}
}else {
dos.write("F02".getBytes(Charset.defaultCharset()));
System.out.println("文件不存在");
continue;
}
//响应结果给客户端
dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
dos.write("F00".getBytes(StandardCharsets.UTF_8));
while ((lenFile=dis.read(temFile))!=-1){
dos.write(temFile,0,lenFile);
}
System.out.println("文件响应成功");
}catch (IOException e) {
e.printStackTrace();
try{
dos.write(("F03"+e.getMessage()).getBytes(StandardCharsets.UTF_8));
System.out.println("捕获异常:"+e.getMessage());
}catch (IOException ioException){
ioException.printStackTrace();
}
}finally {
close(dos,dis,is,socket);
}
}
}
public void close(DataOutputStream dos,DataInputStream dis,InputStream is,Socket socket){
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ServeSocket serveSocket = new ServeSocket();
Thread thread = new Thread(serveSocket);
thread.start();
}
}
客户端
客户端将需要下载的文件名发到服务端后,需调用socket.shutdownOutput(),如果不加如下代码就会阻塞,因为服务器会一直等待客户端的输出
package com.utils.socketFile;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class ClientSocket {
//文件保存路径
private static String filePath = "C:\\Users\\Desktop\\保存\\";
private static String ip = "localhost";
private static int port = 1128;
public static String downloadFile(String fileName) {
Socket socket = null;
DataInputStream dis = null;
DataOutputStream dos = null;
OutputStream os = null;
String flag;
try {
//创建客户端
socket = new Socket(ip, port);
//上传需要下载的文件名
os = socket.getOutputStream();
os.write(fileName.getBytes(StandardCharsets.UTF_8));
//如果不加如下代码就会阻塞,因为服务器会一直等待客户端的输出。
socket.shutdownOutput();//表示客户端已完成通过 TCP 连接发送任何数据
//接受服务端文件并保存
dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filePath + fileName)));
//获取文件状态 F00文件存在 F01文件过大 F02文件不存在 F03服务端异常 F04客户端异常
byte[] temFlag = new byte[3];
dis.read(temFlag);
flag = new String(temFlag);
if (!flag.equals("F00")){
socket.shutdownInput();
System.out.println("文件不存在");
return flag;
}
//获取文件缓冲区
byte[] temFile = new byte[8192];
int lenFile;
while ((lenFile=dis.read(temFile))!=-1){
dos.write(temFile,0,lenFile);
}
System.out.println("文件下载成功");
return flag;
} catch (IOException e) {
e.printStackTrace();
return "F04";
} finally {
close(dos,dis,os,socket);
}
}
public static void close(DataOutputStream dos,DataInputStream dis,OutputStream os,Socket socket){
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
downloadFile("xxxxxxx.pdf");
}
}