2012-03-29 14 views
0

サーバー側でデータを受信する際にいくつか問題があります。ここでは、コードになります。クライアント側でBufferedInputStreamを使用してサーバー側でデータを受信

を私は持っている:

サーバーの一部で
public void sendMessage(byte[] bytes) throws IOException { 
    byte[] lenghtInBytes = ByteBuffer.allocate(4).putInt(bytes.length).array(); 
    out.write(lenghtInBytes,0,4); 
    out.write(bytes,0,bytes.length); 
    out.flush(); 
} 

私が持っている機能:

public byte[] receiveMessage() throws IOException, ClassNotFoundException { 
    byte[] lenghtInBytes = new byte[4]; 
    in.read(lenghtInBytes,0,4); 
    int length = ByteBuffer.wrap(lenghtInBytes).getInt(); 
    serverLogger.debug(length); 
    byte[] data = new byte[length]; 
    in.read(data,0, length); 
    serverLogger.debug(new String(data)); 
    return data; 
} 

サーバーの主:クライアントのメインで

out = new BufferedOutputStream(sslClientSocket.getOutputStream()); 
out.flush(); 
in = new BufferedInputStream(sslClientSocket.getInputStream()); 
System.out.println(new String(receiveString())); 
System.out.println(new String(receiveString())); 

sendMessage(firstData.getBytes()); 
sendMessage(secondData.getBytes()); 

結果として、サーバー側では最初のデータのみが正しく受信され、2番目のデータは空(0)です。なぜこれが起こるのですか?

答えて

0

この問題は、クライアント側アプリケーションがjre7上で実行されている間に、サーバー側でjre6が使用されていたことが原因でした。

0

BufferedInputStream.read(byte [] b、int off、int len)は、使用可能なバイトのみを読み取ります。すべてのバイトを読み込むには、ループ内でin.read()をラップする必要があります。

+0

"...便利な点として、基になるストリームのreadメソッドを繰り返し呼び出すことで、できるだけ多くのバイトを読み込もうとしています...." form here:http://docs.oracle.com/javase /1.4.2/docs/api/java/io/BufferedInputStream.html – savionok

関連する問題