我正在尝试编写一个与服务器建立套接字连接的Applet,并从该服务器接收FFT数据,计算频谱图并显示它。目前,这就是我在C中所拥有的。
int getData(){
int i;
int constant;
// get as many bytes in the socket to fill up the buffer
n = recv(sockfd, tempBuf + readCount, length - readCount, MSG_DONTWAIT);
if(n>0)
readCount += n;
if(readCount == length) //when get enough data
{
// check header constant
constant = ((int*)(tempBuf))[0];
fprintf(stderr, "\nReading header... ");
printf("header.constSync is %X\n", constant);
if(constant != 0xACFDFFBC)
error1("ERROR reading from socket, incorrect header placement\n");
//put data into a buffer
for( i = 0 ; i < samp_rate; i++)
buffer[i] = ((double*)(tempBuf + sizeof(struct fft_header)))[i];
fprintf(stderr, "Reading data... ");
//shift
shift();
readCount = 0;
}
return 1;
}
然而,我也在Java中编写了一个类似的方法,我希望能够完成同样的事情。这是正确的吗?
public int getData() throws IOException {
int constant;
BufferedInputStream data = null;
try{
data=new BufferedInputStream(socket.getInputStream());
} catch (UnknownHostException e){
System.err.println("Invalid Host");
}
catch (IOException e){
System.err.println("Couldn't get the I/O for the connection to the host");
}
int numBytes = data.available();
if(numBytes >0){
readCount+=numBytes;
}
if(readCount == length){
constant = tempBuff[0];
System.out.println("Reading Header");
System.out.println(constant);
if(constant != 0xACFDFFBC){
System.err.println("Error reading from Socket. Incorrect Header Placement");
}
for(int i=0; i<samp_rate; i++){
buffer[i] = tempBuff[i];
System.out.println("Reading data...");
}
}
return 1;
}
**编辑 - 抱歉,我忘记发布实际问题了。我想问的是我正确使用bufferedInputStream吗?或者我应该使用DataInputStream?另外我知道available()用于确定要读取的字节数。我用它了吗?
答案 0 :(得分:1)
你应该完全清楚它不起作用,除非你甚至不打算尝试它,在这种情况下,你根本没有任何业务可以在这里发布。有:
available()
constant
您应该使用DataInputStream
的设施:readInt(),
readDouble(),
readFully(),
等。将BufferedInputStream
包裹在DataInputStream
中开始调用这些方法。