使用Socket和ServerSocket上传文件

本文介绍了一个简单的Java程序,演示了如何通过Socket进行文件上传和接收操作。包括客户端将文件发送到服务器,服务器接收到文件并保存,以及服务器向客户端返回确认消息的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class UploadClient {
public static void main(String[] args) throws IOException {
	String path="D:\\1.jpg";
	Socket socket=new Socket("192.168.1.102",9888);
	BufferedInputStream bi=new BufferedInputStream(new FileInputStream(path));
	OutputStream os=socket.getOutputStream();
	byte[] b=new byte[1024];
	int length=0;
	while((length=bi.read(b))>0){
		os.write(b, 0, length);
	}
	socket.shutdownOutput();
	System.out.println("$$$$$$$$$$$$$$$$$$");
	InputStream is=socket.getInputStream();
	byte[] bs=new byte[1024];
	int len=is.read(bs);
	String returndata=new String(bs,0,len);
	System.out.println("服务端返回的信息:"+returndata);
	
	bi.close();
	os.close();
	is.close();
}
}
public class UploadServer {
public static void main(String[] args) throws IOException {
	ServerSocket server=new ServerSocket(9888);
	Socket socket=server.accept();
	InputStream is=socket.getInputStream();
	BufferedInputStream bi=new BufferedInputStream(is);
	BufferedOutputStream bo=new BufferedOutputStream(new FileOutputStream("D:\\1copy.jpg"));
	byte[] bs=new byte[1024];
	int len=0;
	while((len=bi.read(bs))>0){
		bo.write(bs, 0, len);
		System.out.println(len);
	}
	OutputStream os=socket.getOutputStream();
	os.write("上传成功".getBytes());
	bi.close();
	os.close();
	bo.close();
	is.close();
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值