网络编程:上传文件

服务器端

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/** 
* @author  万星明
* @version 创建时间:2018年10月22日 下午5:16:27 
* 类说明 

*/
public class Server {
	public static void main(String[] args) throws Exception {
		
		//创建socket服务器对象
		@SuppressWarnings("resource")
		ServerSocket ss = new ServerSocket(9999);
		System.out.println("与服务器连接中");
		//监听客户端并接收一个客户端
		Socket socket = ss.accept();
		//创建网络读取流
		BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
		//创建本地写入流
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(""));
		//边读取网络中的数据,边写入本地
		byte[] b = new byte[1024];
		int len = bis.read(b);
		while(len!=-1) {
			//边读边写
			bos.write(b, 0, len);
			bos.flush();
			len = bis.read(b);
			
		}
		System.out.println("客户端上传成功");
		//关流
		ObjectClose.close(bis,bos);
	}
}

客户端

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.net.Socket;
/** 
* @author  万星明
* @version 创建时间:2018年10月22日 下午5:09:43 
*/
public class Client {
	public static void main(String[] args) throws Exception {
		
		//创建socket
		Socket socket = new Socket("127.0.0.1",9999);
		//创建本地的读取流
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(""));
		//创建网络的写入流,将读取的文件内容读取到服务器
		BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
		//边从本地读取文件,边将文件写入到网络上的服务上
		byte[] b = new byte[1024];
		int len = bis.read(b);
		while(len!=-1) {
			//边读取边写入网络中
			bos.write(b,0,len);
			bos.flush();
			
			len = bis.read(b);
			
		}
		System.out.println("上传结束");
		//关流
		ObjectClose.close(bis,bos,socket);
		
	}
}

工具类,用来关闭流

import java.io.Closeable;


/** 
* @author  万星明
* @version 创建时间:2018年10月22日 下午4:05:24 
* 类说明 

*/
public class ObjectClose  {
	
	//关闭方法,关闭所有
	public static void close(Closeable...c) {
		//遍历传入的,关闭
		for (Closeable closeable : c) {
			try {
				closeable.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值