TCP文件上传Java_java 基于TCP协议的文件上传

参考文档

1.https://www.sxt.cn/Java_jQuery_in_action/ten-filebytestream.html

2.https://www.sxt.cn/Java_jQuery_in_action/ten-bufferedbyte.html

参考视频

https://www.bilibili.com/video/BV1ct411n7oG?p=245

1.代码功能

客户端上传文件到服务器端

2.学习重点

1.文件字节流

2.缓冲字节流

3.客户端代码

1.注意输入流是FileInputStream

2.把客户端的输入流经过缓存数组读写入到客户端的输出流

package com.sxt.tcp;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.net.UnknownHostException;

public class FileClient {

public static void main(String[] args) throws UnknownHostException, IOException {

//1.建立连接:使用Socket创建客户端+服务的地址和端口

System.out.println("=================client================");

Socket client=new Socket("localhost",8888);

//2.操作:拷贝 上传

InputStream is=new BufferedInputStream(new FileInputStream("src/ndl.png"));

OutputStream os=new BufferedOutputStream(client.getOutputStream());

byte[] flush=new byte[1024];

int len=-1;

while((len=is.read(flush))!=-1) {

os.write(flush,0,len);

}

os.flush();

//3.释放资源

os.close();

is.close();

client.close();

}

}

4.服务器端代码

1.注意输出流是FileOutputStream

2.把客户端的输出流经过缓存数组读写入到服务器端输出流

package com.sxt.tcp;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class FileServer {

public static void main(String[] args) throws IOException {

// 1.指定端口 使用ServerSocket创建服务器

ServerSocket server=new ServerSocket(8888);

// 2.阻塞式等待连接 accept

Socket client=server.accept();

System.out.println("一个客户端建立了连接");

//3.操作:文件拷贝 存储

InputStream is=new BufferedInputStream(client.getInputStream());

OutputStream os=new BufferedOutputStream(new FileOutputStream("src/tcp.png"));

byte[] flush=new byte[1024];

int len=-1;

while((len=is.read(flush))!=-1) {

os.write(flush,0,len);

}

os.flush();

os.close();

is.close();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值