socket通讯下载文件

服务端

监听需要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");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中的Socket通讯是一种用于在设备之间进行网络通信的方式。通过Socket,Android应用可以与远程服务器或其他设备建立连接,并进行数据的发送和接收。 在Android中,可以使用Java提供的Socket类来实现Socket通讯。以下是一个简单的示例代码,演示了如何在Android应用中建立Socket连接并发送数据: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class SocketClient { private Socket socket; private PrintWriter out; private BufferedReader in; public void connect(String serverIp, int serverPort) { try { // 创建Socket对象,指定服务器IP和端口号 socket = new Socket(serverIp, serverPort); // 获取输入输出流 out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 发送数据 out.println("Hello, server!"); // 接收服务器返回的数据 String response = in.readLine(); System.out.println("Server response: " + response); // 关闭连接 socket.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,首先创建一个Socket对象,指定要连接的服务器的IP地址和端口号。然后通过获取输入输出流进行数据的发送和接收。在示例中,我们发送了一条字符串"Hello, server!"到服务器,并接收服务器返回的数据。 需要注意的是,在Android应用开发中,网络操作涉及到网络权限的配置。在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 这样就可以在Android应用中使用Socket进行网络通信了。当然,为了避免在主线程中进行网络操作,通常会将Socket通信放在子线程或者使用异步任务来处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值