公司现在要求java(服务器)与vC++(客户端)
进行socket通信,协议已经定义好了,
就是不知道怎么对数据包(结构)进行组装和拆分。
结构如下:
public class MessageStruct { /** 消息长度 */
private int length;
/** 消息类型 */
private int type;
/** 消息协议 */
private int treaty;
/** 消息版本 */
private String version;
/** 消息体 */
private String body;
public int getLength() {
return length;
} public void setLength(int length) {
this.length = length;
} public int getType() {
return type;
} public void setType(int type) {
this.type = type;
} public int getTreaty() {
return treaty;
} public void setTreaty(int treaty) {
this.treaty = treaty;
} public String getVersion() {
return version;
} public void setVersion(String version) {
this.version = version;
} public String getBody() {
return body;
} public void setBody(String body) {
this.body = body;
} }
在java中我把结构做为一个类来处理,现在就是在发送的时候把 new 一个MessageStruct对象 在把值set进去
然后用 PrintWriter pwr = new PrintWriter(socket.getOutputStream()); pwr.println(MessageStruct对象);
还要不要对 值的类型转成byte再println发送出去呢? 很急,希望大虾发一个例子!!
进行socket通信,协议已经定义好了,
就是不知道怎么对数据包(结构)进行组装和拆分。
结构如下:
public class MessageStruct { /** 消息长度 */
private int length;
/** 消息类型 */
private int type;
/** 消息协议 */
private int treaty;
/** 消息版本 */
private String version;
/** 消息体 */
private String body;
public int getLength() {
return length;
} public void setLength(int length) {
this.length = length;
} public int getType() {
return type;
} public void setType(int type) {
this.type = type;
} public int getTreaty() {
return treaty;
} public void setTreaty(int treaty) {
this.treaty = treaty;
} public String getVersion() {
return version;
} public void setVersion(String version) {
this.version = version;
} public String getBody() {
return body;
} public void setBody(String body) {
this.body = body;
} }
在java中我把结构做为一个类来处理,现在就是在发送的时候把 new 一个MessageStruct对象 在把值set进去
然后用 PrintWriter pwr = new PrintWriter(socket.getOutputStream()); pwr.println(MessageStruct对象);
还要不要对 值的类型转成byte再println发送出去呢? 很急,希望大虾发一个例子!!
跨语言类型匹配,字符编码匹配,比较麻烦的问题呢。首要问题是制定消息的二进制格式,要方便两种语言用,不妨和C++程序员一起商量。直接把对象送出去肯定是不行的喽。有熟悉ORB的没?喊他们做很快的啦。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(this.length);
out.writeInt(this.type);
out.writeInt(this.treaty);
out.writeByte(version.getByte());
out.writeByte(body.getByte());
out.writeByte(Msg_level);
return bos.toByteArray();
}
不同语言间的通信你仍个对象过去?
你只能按照给你的协议将你的实体对象中的数据转换为byte发送过去。
非常简单。