服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java与c/c++进行socket通信的一些问题(1)


  近几天看到csdn上问c/c++和java通信的问题比较多,特别是c特有的数据结构(如struct)。

特地根据网友的一个问题举个例子,希望对初学者有所帮助。

原问题见:http://community.csdn.net/expert/topic/3886/3886989.xml?temp=.3527033

这类问题通常是为了利用原有server或者server不能做修改(通常是c/c++)造成。

比如server端只接收一个结构employee,定义如下:

struct userinfo {
char username[20];
int userid;
};
struct employee {
userinfo user;
float salary;
};
当然也可以定义为

struct employee {
char name[20];
int id;
float salary;
};


java client 测试源码(为说明问题,假设struct字节对齐,sizeof(employee)=28)

import java.net.*;

/**
* 与c语言通信(java做client,c/c++做server,传送一个结构)
* @author kingfish
* @version 1.0
*/
class employee {
private byte[] buf = new byte[28]; //为说明问题,定死大小,事件中可以灵活处理

/**
* 将int转为低字节在前,高字节在后的byte数组
*/
private static byte[] tolh(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}

/**
* 将float转为低字节在前,高字节在后的byte数组
*/
private static byte[] tolh(float f) {
return tolh(float.floattorawintbits(f));
}

/**
* 构造并转换
*/
public employee(string name, int id, float salary) {
byte[] temp = name.getbytes();
system.arraycopy(temp, 0, buf, 0, temp.length);

temp = tolh(id);
system.arraycopy(temp, 0, buf, 20, temp.length);

temp = tolh(salary);
system.arraycopy(temp, 0, buf, 24, temp.length);
}

/**
* 返回要发送的数组
*/
public byte[] getbuf() {
return buf;
}

/**
* 发送测试
*/
public static void main(string[] args) {
try {
socket sock = new socket("127.0.0.1", 8888);
sock.getoutputstream().write(new employee("kingfish", 123456789, 8888.99f).
getbuf());
sock.close();
}
catch (exception e) {
e.printstacktrace();
}

} //end

---------------------------------------------------------------------------

当然,也可以利用writeint,writefloat方法发送,但字节顺序需要改为低在前。
这个问题稍后在讨论。


如有任何问题,请指正!

扫描关注微信公众号