![](/img/trans.png)
[英]The server is sending data through the socket, but the client is not receving it (Java)
[英]Receving FFT data over a socket in Java
我试图编写一个与服务器建立套接字连接并从该服务器接收FFT数据,计算频谱图并显示它的Applet。 目前,这就是我在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()用于确定要读取的字节数。 我使用的对吗?
您应该非常清楚这是行不通的,除非您甚至都没有去尝试它,在这种情况下,您根本没有要发布的业务。 有:
available()
constant
赋值,该变量可以是任何东西 您应该为此使用DataInputStream
功能: readInt(),
readDouble(),
readFully(),
等。将BufferedInputStream
包装在DataInputStream
然后开始调用这些方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.