Java 客户端向服务端上传mp3文件数据的实例代码
客户端:
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文件数据的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
赞 (0)