欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA网络编程实现客户端文件的上传和服务器端文件的下载

程序员文章站 2022-07-01 08:01:24
...

网络编程


  • 客户端文件的上传&&服务器端文件的下载
  • 服务器端下载成功后向客户端返回文件下载成功的消息

Client

package it.bxh.netCS.upload;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/*
 * @author  bxh
 * As a client,it sents a file to the server
 */
public class Client {
	public static void main(String[] args) {
		try {
			//获取一个socket对象
			Socket socket = new Socket("127.0.0.1",8888);
			//获取网络字节输出流
			OutputStream os = socket.getOutputStream();
			//客户端获取本地字节输入流
			FileInputStream fis = new FileInputStream("D://qingshu.txt");
			int len=0;
			byte[] byte1=new byte[1024];
			while((len=fis.read(byte1))!=-1)
			{
				os.write(byte1, 0, len);
			}
			//关闭输出流  防止造成死循环
			socket.shutdownOutput();
			
			//接受服务器端的返回信息
			byte[] by=new byte[1024];
			InputStream stream = socket.getInputStream();
			int len1 = stream.read(by);
			System.out.println(new String(by,0,len1));
			
			
			//关闭资源  暂时就在catch的主程序体中关闭
			stream.close();
			fis.close();
			os.close();
			socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
}
}

Server

package it.bxh.netCS.upload;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*
 * @author bxh
 * As a server,this program is meant to receive the massage that sent from the client.
 */
public class Server {
	public static void main(String[] args) {
		try {
			//获取serversocket对象
			ServerSocket serverSocket = new ServerSocket(8888);
			//获取到客户端的socket对象
			Socket socket = serverSocket.accept();
			//服务器端获取网络字节输入流
			InputStream is = socket.getInputStream();
			int len=0;
			byte[] by=new byte[1024];
			//获取本地文件输出流
			FileOutputStream fos =new FileOutputStream("F://a.txt");
			
			while((len=is.read(by))!=-1)
			{
				fos.write(by, 0, len);
			}
		
			//获取网络字节输出流,像客户端发送消息
			OutputStream os = socket.getOutputStream();
			os.write("文件下载成功".getBytes());
			
			
			//释放资源   暂时就放在try的结构体中
			os.close();
			fos.close();
			is.close();
			socket.close();
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

相关标签: JAVA后端开发