2017-01-24 10 views
0

送信者/受信者コードがクライアントからサーバーに画像ファイル(49692バイト)を転送しようとしたとき(UDPソケットを使用します)。バイトリストのサイズがバイトバッファと正確に同じですが、例外(受信側の行番号30に記載)。どんな助け?はBufferOverflow例外を解決できません - Java

送信側:

public class P_Sender 
{ 
    public static DatagramSocket sock =null; 
    public static DatagramPacket sendPacket,recvPacket=null; 
    public static int port=15000; 
    public static InetAddress ip; 
    public static ByteBuffer fileBuffer; 
    public static byte[] sendBytes; 

    public static byte[] int2Byte(int i) throws IOException 
    { 
    ByteArrayOutputStream baos=new ByteArrayOutputStream(Integer.SIZE/4); 
    DataOutputStream dos=new DataOutputStream(baos); 
    dos.writeInt(i); 
    byte[] result=baos.toByteArray(); 
    dos.close();  
    return result; 
    } 

    public static void main(String[] args) throws Exception 
    { 
     FileChannel inChannel = new FileInputStream("abc.jpeg").getChannel(); 
     fileBuffer = ByteBuffer.allocate((int) inChannel.size()); 
     inChannel.read(fileBuffer); 
     inChannel.close(); 
     fileBuffer.flip(); 
     ip=InetAddress.getByName("localhost"); 
     sock=new DatagramSocket(); 
     sendBytes=new byte[fileBuffer.capacity()]; 
     System.out.println("Length:" +fileBuffer.capacity()); 
     fileBuffer.get(sendBytes); 
     sendPacket=new DatagramPacket(sendBytes,sendBytes.length,ip,port); 
     sock.send(sendPacket); 
     System.out.println("sent Packet Length:" +sendPacket.getLength()); 
    } 

} 

レシーバ側:

public class P_Recv 
{ 
    public static DatagramSocket sock; 
    public static DatagramPacket recvDataPacket; 
    public static byte[] recvBytes; 
    public static int port; 
    byte[] dataBuf; 
    public static InetAddress ip; 
    public static ByteBuffer fileBuffer; 

    public static void main(String args[]) throws Exception 
    { 
     SrReceiver srobj=new SrReceiver(); 
     sock=new DatagramSocket(15000); 
     recvBytes=new byte[49692]; 
     recvDataPacket=new DatagramPacket(recvBytes,recvBytes.length); 
     sock.receive(recvDataPacket); 
     System.out.println("Received Packet Length: "+recvDataPacket.getLength()); 
     fileBuffer= ByteBuffer.allocate(recvDataPacket.getLength()); 
     System.out.println(fileBuffer.capacity()); 
     fileBuffer.clear(); 
     fileBuffer.flip(); 
     fileBuffer.put(recvBytes);//Here i am thrown BufferOverflowException 
     FileChannel outchannel = new FileOutputStream(new File("abcd.jpeg")).getChannel(); 
     outchannel.write(fileBuffer); 
     outchannel.close(); 
     sock.close(); 
    }//main 
}//class 
+0

'Integer.SIZE/4'? – Kayaman

+0

recvDataPacketはそのサイズですか?あなたはそれをチェックせず、それを使ってバッファを割り当て、さらに書きます。 –

+0

私はそれを送信者の側でチェックしたので、それをハードコードしました。私は、49692が受信側の側に転送されていると確信しています(私もそれを印刷することができます)。 –

答えて

1
put()後に flip()を移動

write()またはフレーバーget()の前にのみ使用されます。 read()またはフレーバーput()の前に使用されていません。

+0

'clear()'を取り除くこともできます。新しいバッファーは既にクリアされています。 – EJP

+0

flip()を削除しました。それは働いた、ありがとう。 –

+0

書き込みの前に戻さない限りはありません。 – EJP

関連する問題