通过套接字在java中正确发送MP3和JPEG文件

时间:2016-07-31 13:02:25

标签: java sockets

SERVER(接收文件)

     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在服务器上创建的文件大小与客户端发送的文件大小相同

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

1 个答案:

答案 0 :(得分:0)

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

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

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