c - 在 Java 中通过套接字接收 FFT 数据



我正在尝试编写一个小程序,该小程序与服务器建立套接字连接并从该服务器接收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 %Xn", constant);
    if(constant != 0xACFDFFBC)
        error1("ERROR reading from socket, incorrect header placementn");
    //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() 用于确定要读取多少字节。我用得对吗?

你应该非常清楚它不起作用,除非你甚至没有费心去尝试它,在这种情况下,你根本没有业务可以在这里发布。有:

  • 滥用available()
  • 从未声明的数组变量中constant赋值,该数组变量可以是任何内容
  • 根本没有实际的阅读。

您应该为此使用 DataInputStream 的功能:readInt(), readDouble(), readFully(),等。 将BufferedInputStream包装在DataInputStream中并开始调用这些方法。

最新更新