【问题标题】:Send MP3 and JPEG file over socket properly over Socket in java在 java 中通过套接字正确地通过套接字发送 MP3 和 JPEG 文件
【发布时间】:2016-08-01 01:36:35
【问题描述】:

服务器(接收文件)

     String ip=JOptionPane.showInputDialog(this,"Enter Port Number :");
      String folder=jTextField2.getText();
      try
      {
       ServerSocket sskt= new ServerSocket(Integer.parseInt(ip));
Socket skt= sskt.accept();
InputStream is= skt.getInputStream();



byte[] bytes= new byte[1024*16];

DataInputStream dis=new DataInputStream(skt.getInputStream());
        String ext=dis.readUTF();

  System.out.println("extension read");



 String path=folder+"/file."+ext;
JOptionPane.showMessageDialog(this, path);
File f= new File(path);
OutputStream output = new FileOutputStream(f);
while(is.read(bytes)>0)
{
  output.write(bytes);
 System.out.println("byte read");
}
System.out.println("Done!!!");

}
 catch(Exception e)
 {
 System.out.println(e);
   }

客户(发送文件)

      String ip=JOptionPane.showInputDialog(this,"enter server ip:");
        String port=JOptionPane.showInputDialog(this,"enter port number :");
         File file=new File(jTextField1.getText());
        String name=file.getName();
       String n=  name.substring(name.lastIndexOf(".") + 1);



        try {
            Socket skt=new Socket(ip, Integer.parseInt(port));
            OutputStream os=  skt.getOutputStream();
            DataOutputStream dos= new DataOutputStream(os);
            dos.writeUTF(n);
            os.flush();


            FileInputStream fis= new FileInputStream(file);
            BufferedInputStream bis= new BufferedInputStream(fis);
            byte[] mybytearray = new byte[(int) file.length()];
            bis.read(mybytearray, 0, mybytearray.length);
            os.write(mybytearray, 0, mybytearray.length);
            JOptionPane.showMessageDialog(this,"Done!!");
            os.close();
        }

        catch (Exception ex) {
            System.out.println(ex);
        }

我能够传输所有格式的文件 bt mp3 和 jpeg 文件无法正确打开。媒体播放器无法播放任何 mp3 文件 bt 服务器创建的文件大小与客户端发送的相同

任何人都可以帮我解决这个问题

【问题讨论】:

    标签: java sockets


    【解决方案1】:

    常见问题:忽略read() 返回的长度。您的复制循环应如下所示:

    while ((count = is.read(bytes)) > 0)
    {
        output.write(bytes, 0, count);
    }
    

    您不需要客户端中关于分配正确大小的缓冲区的所有垃圾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      相关资源
      最近更新 更多