import java.net.*;
import java.io.*;
/**
* 与c语言通信(java做client,c/c++做server,传送一个结构)
* @author kingfish
* @version 1.0
*/
public class employee2 {
private string name;
private int id;
private float salary;
/**
* 将int转为低字节在前,高字节在后的int
*/
private static int tolh(int in) {
int out = 0;
out = (in & 0xff) << 24;
out |= (in & 0xff00) << 8;
out |= (in & 0xff0000) >> 8;
out |= (in & 0xff000000) >> 24;
return out;
}
/**
* 将float转为低字节在前,高字节在后的int
*/
private static int tolh(float f) {
return tolh(float.floattorawintbits(f));
}
/**
* 构造并转换
*/
public employee2(string name, int id, float salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
/**
* 取得名字,定长byte数组
*/
public byte[] getname() {
byte[] b = new byte[20];
system.arraycopy(name.getbytes(), 0, b, 0, name.getbytes().length);
return b;
}
/**
* 取得编号(低字节在前)
*/
public int getid() {
return tolh(id);
}
/**
* 取得工资(低字节在前)
*/
public int getsalary() {
return tolh(salary);
}
/**
* 发送测试
*/
public static void main(string[] args) {
try {
employee2 p = new employee2("kingfish", 123456789, 8888.99f);
socket sock = new socket("127.0.0.1", 8888);
dataoutputstream dos = new dataoutputstream(sock.getoutputstream());
dos.write(p.getname());
dos.writeint(p.getid());
dos.writeint(p.getsalary());
sock.close();
}
catch (exception e) {
e.printstacktrace();
}
}
} //end
-----------------------------------------------------------------------------------------------------
如有任何问题,请指正!
kingfish
文章整理:站长天空 网址:http://www.z6688.com/
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!




