在过去的几天里,我一直被一个问题所困扰,坦率地说,我已经没有主意了。我想做的是使用Jersey托管一个rest服务,该服务将在其有效载荷中接受带有音频数据流的post请求。
问题我一直遇到的是,我松散的数据一致性(我在客户端和服务器上运行CRC检查),并且在发送的数据和接收的数据之间的1024字节缓冲区CRC的8读取后变得不一致。当我处理较小尺寸的文本或内容时,它工作得很好。代码是附件,谁能告诉我我做错了什么?
服务器:@POST
@Consumes("audio/wav")
@Produces(MediaType.TEXT_PLAIN)
public String streamCommand(@Context HttpServletRequest request ) throws Exception
{
CRC32 crc = new CRC32();
InputStream stream = request.getInputStream();
byte[] readBuffer = new byte[1024];
StringBuilder builder = new StringBuilder();
while (stream.read(readBuffer) > -1)
{
crc.update(readBuffer);
builder.append(new String(readBuffer));
System.out.println(crc.getValue());
}
return builder.toString();
}
客户:static final String SOUND_FILE_NAME = "SoundTest.wav";
@BeforeClass
public static void setup() throws Exception
{
soundStream = classloader.getResourceAsStream(SOUND_FILE_NAME);
}
@Test
public void test() throws Exception {
PipedOutputStream stream = new PipedOutputStream();
DataStreamer data = new DataStreamer(stream, soundStream);
ExecutorService executor = Executors.newFixedThreadPool(1);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8080/EVAFrontEnd/webapi/users/1/devices/1/command");
post.addHeader(HttpHeaders.CONTENT_TYPE, "audio/wav");
InputStreamEntity requestEntity = new InputStreamEntity(new PipedInputStream((PipedOutputStream) stream), -1);
post.setEntity(requestEntity);
executor.execute(data);
executor.shutdown();
HttpResponse r = client.execute(post);
assertNotNull(r);
}
数据等浮电缆:
public class DataStreamer implements Runnable {
OutputStream writeStream;
CheckedInputStream readStream;
static Logger logger = Logger.getLogger(DataStreamer.class);
public DataStreamer(OutputStream stream, InputStream readingStrem) {
this.writeStream = stream;
this.readStream = new CheckedInputStream(readingStrem, new Adler32());
}
@Override
public void run()
{
CRC32 crc = new CRC32();
try {
byte[] buffer = new byte[1024];
while (readStream.read(buffer) > -1) {
crc.update(buffer);
System.out.println(crc.getValue());
writeStream.write(buffer);
}
System.out.println("END CRC");
readStream.close();
writeStream.close();
}
catch (Exception e) {
logger.error("Unable to stream data.", e);
}
}
}
谢谢!
您需要始终保存
写入的字节数bytes_read = readStream.read(buffer);
放入变量中,因为该方法有时会给出较短的结果。然后使用ArrayList。copyOfRange创建子数组[0…]Bytes_read-1]从缓冲区中读取有效字节。