[size=11px][size=10px]我用服务器端建立了一个UDP的Socket,监听接受客户端传来的包。但是客户端是C语言写的,一个命令格式是一个结构体;
java中没有结构体,我在服务器端只能建立一个类封装这个命令格式。我要提问的是如何将客户端结构体中的成员数据传到java那个类的成员中?
这是这个类,按照C的结构体设计。
public class StructCommandData {
       byte commandtype;
       int sourceip;
       int sourceport;
       byte dst[]=new byte[6];
       int priv_length;
       public StructCommandData(){
        
       }
       public StructCommandData(byte commandtype,int sourceip,int sourceport,byte dst[],int priv_length){
           this.command_type=command_type;
           this.source_ip=source_ip;
           this.source_port=source_port;
           this.dst_mac=dst_mac;
           this.priv_length=priv_length;
          
       }}
服务器端
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
public class SocketPart {
DatagramSocket toRoutersock=null;

SocketPart(){
try {
toRoutersock = new DatagramSocket(2120);
byte[] buf = new byte[1024];//接受结构体中各个成员数据
DatagramPacket p =new DatagramPacket(buf,buf.length);//打包; 
toRoutersock.receive(p);//将数据包接受到服务器端
//请问:然后如何将p.getDate()中的数据为java这个StructCommandData 类赋值?
  且如果回传到客户端的话,如何按照C的结构体读取数据呢?


} catch (SocketException e) {
System.err.println("Can't open socket");
      System.exit(1); } catch (IOException e) {
System.err.println("Communication error");
      e.printStackTrace(); }
    
}   

}
[/size][/size]

解决方案 »

  1.   

    我提示一句:
    既然是UDP标准协议,就不会区分是哪种语言了,否则就不叫协议了!
    C里面的UDP和Java里面的UDP在协议和数据传输上没有任何区别,只有编程语法的区别。java方面全当是java发来的就行了
      

  2.   

    1 楼一语中的,佩服!^_^建议用 DataInputStream 把收到的数据包装一下,然后按协议的约定一个一个读出来就是了:ByteArrayInputStream bis = new ByteArrayInputStream(p.getDate());
    DataInputStream dis = new DataInputStream(bis);
    structCommandData.commandtype = dis.readByte();
    structCommandData.sourceip = dis.readInt();
    structCommandData.sourceport = dis.readInt();
    ...
      

  3.   

    .........
    假如我的C程序一个int占8个byte也用dis.readInt(); 读?
    那么要不要考虑Big-ending & Little-ending?
    建议楼主直接传字符串比较方便