【发布时间】:2015-07-09 12:14:50
【问题描述】:
Java 中的套接字编程新手!。我正在尽我最大的努力去理解 Java 套接字编程,以及如何像数据包一样解码“C”支柱。
客户端是python,它在标签之间发送数据包,
有效载荷示例:<tag1> data packet 1</tag1><tag2>data packet 2</tag2>
有一个接收payload的c代码,解码payload的结构体,所有tag都是30字节,数据包1、2、..n的结构不同
我是java程序的新手,通过网络搜索后,我可以编写一个从客户端接收有效负载的套接字服务器,现在在解码数据包时遇到问题。 我可以显示字节。所以使用 Arrays.copyOfRange 方法获取数据。
数据包数据如下所示,
typedef struct {
unsigned char dataType;
unsigned char value[4];
} GEN_VAL
typedef struct {
unsigned char dataType;
unsigned char numBytes;
unsigned char value[32];
} GEN_STR_32;
typedef struct {
char startTag[32];
GEN_STR_32 c_code;
GEN_STR_32 c_name;
GEN_STR_32 c_info;
GEN_VAL i_type;
GEN_VAL i_count1;
GEN_VAL i_count2;
char endTag[32];
} DATA_PACKET_1;
我收到带有以下代码 sn-p 的缓冲区
DataInputStream inStream = new DataInputStream
(new BufferedInputStream(socket.getInputStream()));
while ( ( noOfBytes = (int)inStream.read(recvBuff)) != -1)
{
cDecode mydecode = new cDecode();
mydecode.decodePacket(noOfBytes, recvBuff);
}
cDecode.java
public void decodePacket(int TotalBytes, byte[] BuffRecv)
{
byte[] GetTag = new byte[32];
byte[] GEN_STR_32 = new byte[32];
byte[] GEN_INT_4 = new byte[4];
GetTag = Arrays.copyOfRange(BuffRecv,0,31);
String TagStr = new String(GetTag).trim(); //get start tag
int startloc = 31;
int offset = startloc + 32;
GEN_STR_32 = Arrays.copyOfRange(Buff,startloc,offset);
String cCode = new String(GEN_STR_32).trim(); // get value of cCode
System.out.println("Code :" + cCode );
startloc = offset;
offset = startloc + 32;
GEN_STR_32 = Arrays.copyOfRange(Buff,startloc,offset);
String cName = new String(GEN_STR_32).trim(); //get value of cName
System.out.println("Name:" + cName );
startloc = offset;
offset = startloc + 32;
GEN_STR_32 = Arrays.copyOfRange(Buff,startloc,offset);
String cInfo = new String(GEN_STR_32).trim(); //get value of cName
System.out.println("Info:" + cInfo );
startloc = offset;
offset = offset + 4;
ByteBuffer iTypeByteBuff = ByteBuffer.wrap(GEN_DATA_INT_4);
int iType= iTypeByteBuff .getInt();
System.out.println("type :" + iType);
startloc = offset;
offset = offset + 4;
// likewise used ByteBuffer for remaining integer data
// for receiving end tag, offset is added with 32!
}
前 3 个数据是字符串值和
第二个3数据有整数值
字符串值显示正确。
在将字节转换为整数时发现问题,不确定我是否在 Arrays.copyOfRange 方法中使用了正确的 startloc 和偏移值。
我根据从网上获得的信息进行了尝试。
我还读到了一个单独的类,它没有用于所有数据结构的方法。但我找不到任何完整的示例,因为 java 中没有“sizeof”。
有人可以指导我在这种情况下解码数据包的正确方法吗?
【问题讨论】: