简易的文件下载功能

该示例展示了如何使用Java实现一个简单的TCP/IP通信。服务器端创建了一个ServerSocket,监听8899端口,当客户端连接时启动新线程处理请求。服务器向客户端发送文件'H:/test.png'的内容,客户端接收并保存为'H:/out.png'。此代码实现了基本的文件传输功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务器端

public class ServiceSocket {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8899);
            while(true){
                System.out.println("服务器启动...");
                Socket socket = serverSocket.accept();
                System.out.println("感知到客户端连接...");
                new Thread(new MyThread(socket)).start();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class MyThread implements Runnable{

        private Socket socket ;

        public MyThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            OutputStream outputStream = null ;
            FileInputStream fileInputStream = null;
            try {
                 outputStream = socket.getOutputStream();

                 fileInputStream = new FileInputStream(new File("H:/test.png"));

                byte[] bytes = new byte[64] ;

                int len = -1 ;
                while ( (len = fileInputStream.read(bytes))!=-1){
                    outputStream.write(bytes,0,len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try{
                    if(outputStream!=null) outputStream.close();
                    if(fileInputStream!=null) fileInputStream.close();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

客户端

public class ClientSocket {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",8899);
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[64] ;

        FileOutputStream fileOutputStream = new FileOutputStream(new File("H:/out.png"));

        int len = -1 ;
        while ((len = inputStream.read(bytes))!=-1){
            fileOutputStream.write(bytes,0,len);
        }

        inputStream.close();
        fileOutputStream.close();



    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值