Socket通信实现文件传输

客户端:

package src.com.zhang.socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class FileClient {
    public static void main(String[] args) throws Exception{
        //客户端连接服务端8888,得到Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        //创建读取磁盘文件的输入流
        String filePath="C:\\Pictures\\Saved Pictures\\yingping.jpg";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] bytes = steamToByteArray(bis);
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(bytes);

        bis.close();
        socket.shutdownOutput();
        bos.close();
        socket.close();

    }
    public static byte[] steamToByteArray(InputStream is) throws Exception{
        ByteArrayOutputStream bos=new ByteArrayOutputStream();//创建输出流对象
        byte[] b=new byte[1024];
        int len;
        while ((len=is.read(b))!=-1){
            bos.write(b,0,len);//把读取的数据写入bos
        }
        byte[] array= bos.toByteArray();
        bos.close();
        return array;
    }
}

服务端:

package src.com.zhang.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileSercer {
    public static void main(String[] args) throws Exception{
        //1.服务端在本机监听8888端口
        ServerSocket serverSocket=new ServerSocket(8888);
        System.out.println("服务端监听...");
        //2.等待连接
        Socket socket=serverSocket.accept();
        //3.读取客户端发送的数据
        //通过Socket得到输入流
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes=steamToByteArray(bis);
        //4.将得到bytes[]数组,写入到指定路径,就得到指定文件
        String destFilePAth="src\\1.png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePAth));
        bos.write(bytes);

        bos.close();
        bis.close();
        socket.close();
        serverSocket.close();
    }

    public static byte[] steamToByteArray(InputStream is) throws Exception{
        ByteArrayOutputStream bos=new ByteArrayOutputStream();//创建输出流对象
        byte[] b=new byte[1024];
        int len;
        while ((len=is.read(b))!=-1){
            bos.write(b,0,len);//把读取的数据写入bos
        }
        byte[] array= bos.toByteArray();
        bos.close();
        return array;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值