请教java的网络传输中数据处理的问题

城中企鹅 2008-01-21 08:24:07
[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]
...全文
143 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Squall1009 2008-02-18
  • 打赏
  • 举报
回复
.........
假如我的C程序一个int占8个byte也用dis.readInt(); 读?
那么要不要考虑Big-ending & Little-ending?
建议楼主直接传字符串比较方便
maquan 2008-02-18
  • 打赏
  • 举报
回复
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();
...
xufei547 2008-02-18
  • 打赏
  • 举报
回复
转成字节数组就可以了
城中企鹅 2008-01-22
  • 打赏
  • 举报
回复
谢谢你啦
哦,这样啊~好的,我试试。
老紫竹 2008-01-22
  • 打赏
  • 举报
回复
我提示一句:
既然是UDP标准协议,就不会区分是哪种语言了,否则就不叫协议了!
C里面的UDP和Java里面的UDP在协议和数据传输上没有任何区别,只有编程语法的区别。

java方面全当是java发来的就行了

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧