【java】使用TCP,socket和server socket传输一个文件的例子

模拟的过程是:A 给 B 发送一个文件。
A 是发送端, B 是接收端。

使用tcp套接字。

使用了:

ServerSocket ss = new ServerSocket(int 端口号);//接收端
Socket s = ss.accept();//接收端
Socket s=new Socket(String IP地址, int 端口);//发送端
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(String 文件路径+文件名));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(String 文件路径+文件名));

文件路径格式可以是:
"D:\\....\\....\\文件名"

比特数组:
byte[] buf=new byte[1024];

循环读取
int b;
while((b=bis.read(buf))!=-1){
    fos.write(buf,0,b);
    fos.flush();
}

发送端 A:

BufferedInputStream 通过new FileInputStream()方法 从本地读取一个文件,BufferedOutputStream 中的FileOutputStream 实例是通过 s.getOutputStream() 方法获得的,要发送到网络中某个主机。

接收端 B:

与发送端相反,或者说相对应。
BufferedInputStream 中的 FileInputStream 通过 s.getInputStream() 获得,从网络中获取,BufferedOutputStream 通过 new FileOutputStream()方法 把文件写到本地路径。

代码:
发送端:

try {
            Socket s=new Socket("127.0.0.1",端口);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\file\\tee"));
            BufferedOutputStream fos = new BufferedOutputStream(s.getOutputStream());

            byte[] buf=new byte[1024];
            int b;
            while((b=bis.read(buf))!=-1){
                fos.write(buf,0,b);
                fos.flush();
            }

            fos.close();
			bis.close();
			
        } catch (IOException exception) {
            exception.printStackTrace();
        }

接收端:

 try {

            ServerSocket ss = new ServerSocket(端口);
            Socket s = ss.accept();

            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\otherfile\\tee"));

            byte[] buf=new byte[1024];
            int b;
            while((b=bis.read(buf))!=-1){
                fos.write(buf,0,b);
                fos.flush();
            }
            
            fos.close();
            bis.close();

        } catch (IOException exception) {
            exception.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值