JAVA 与C SOCKET连接传输数据格式的问题,调试了很多办法。偶没折了。
程序是基与TCP的SOCKET连接,
下面是JAVA客户端的相关程序:
//数据定义
short idl=1,adl=16,dal=8;
data1=new DataTable(idl,adl,dal);//数据全部初始为0
data1.ad[0]=5.0f;
data1.ad[1]=37.7f;
data1.ad[2]=9.35f;
data1.ad[3]=73.0f;
data1.ad[5]= 33.63f;
data1.da[0]=20.0f;
data1.da[5]=38.3f;
data1.da[7]=7.56f;
//数据发送
out.writeUTF("DATA"); out.flush();
out.writeShort(data.id); out.flush();
out.writeShort(data.adl); out.flush();
out.writeShort(data.dal); out.flush();
float temp;
for(int i=0;i<data.adl;i++){
temp=data.ad[i];
if(temp!=0.0) temp+=add;
out.writeFloat(temp);
out.flush();
}
下面是我的接受程序,LINUX C
char buf[20];
int r=read(client_sockfd,buf,sizeof(buf));
buf[r]='\0';
for(count=0;count<3;count++;){
r=read(client_sockfd,&temp,sizeof(int));
id[count]=ntohs(temp);
printf(", %d",id[count]);
}
for(i=0;i<3;i++){
for(j=0;j<id[i];j++){
r=read(client_sockfd,buf,sizeof(buf));
buf[r]='\0';
printf(" %s",buf);
float ff=*(flaot*)buf;
printf(" %f",ff);
}
}
运行的结果一点规律都没有,下面就是部分内容是:
1,16,8
4 @~ 0.000000
8 BI[][]A** -42801728.000000
12 * 0.000000
1 null 0.000000
(前面INT可以正确接收,后面的FLAOT都是乱码或者益处)
( *是黑色方块,[]表示像德语一样的乱码 )