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

Java 客户端向服务端上传mp3文件数据的实例代码

程序员文章站 2024-02-25 19:47:27
客户端: package cn.itcast.uploadpicture.demo; import java.io.bufferedinputstream;...

客户端:

package cn.itcast.uploadpicture.demo;
import java.io.bufferedinputstream;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.printstream;
import java.net.socket;
import java.net.unknownhostexception;
public class uploadpicclient {
 public static void main(string[] args) throws unknownhostexception, ioexception {
 
// 1、建立客户端的socket服务
 socket s=new socket("192.168.1.216",10012);
 
// 2、获取图片资源
 bufferedinputstream burin=
  new bufferedinputstream(new fileinputstream("f:\\cloudmusic\\罗大佑,黄霑,徐克 - 沧海一声笑.mp3"));
 
// 3、获取socket输出流
 printstream pso=new printstream(s.getoutputstream(),true);
 
// 4、将数据写入到输出流
 byte[]buff=new byte[1024];
 int len=-1;
 while((len=burin.read(buff))!=-1) {
  pso.write(buff, 0, len);
 }
 s.shutdownoutput();
 
// 5、获取服务端的返回的数据
 inputstream is=s.getinputstream();
 byte[]buffin=new byte[1024];
 int lenth=is.read(buffin);
 string str=new string(buffin,0,lenth);
 system.out.println(str);
 
// 6、关闭流
 s.close();
 burin.close();
 }
}

服务端:

package cn.itcast.uploadpicture.demo;
import java.io.bufferedinputstream;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.printstream;
import java.net.serversocket;
import java.net.socket;
public class uploadpicserver {
 public static void main(string[] args) throws ioexception {
 serversocket ss=new serversocket(10012);
 socket s=ss.accept();
 
 system.out.println(s.getinetaddress().gethostaddress()+"connnected.......");
 
 bufferedinputstream burin=new bufferedinputstream(s.getinputstream());
 
 file file=new file("serve.mp3");
 if(!file.exists())
  file.mkdirs();
 printstream ps=new printstream(new fileoutputstream(file),true);
 
 byte[]buff=new byte[1024];
 int len=-1;
 while((len=burin.read(buff))!=-1) {
  ps.write(buff, 0, len);
 }
 
 printstream psout=new printstream(s.getoutputstream(),true);
 psout.println("上传成功");
 
 ss.close();
 s.close();
 ps.close();
 }
}

总结

以上所述是小编给大家介绍的java 客户端向服务端上传mp3文件数据的实例代码,希望对大家有所帮助