国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

java與c/c++進(jìn)行socket通信的一些問題(1)

2019-11-18 14:38:29
字體:
供稿:網(wǎng)友

  近幾天看到csdn上問c/c++和java通信的問題比較多,非凡是c特有的數(shù)據(jù)結(jié)構(gòu)(如strUCt)。

特地根據(jù)網(wǎng)友的一個(gè)問題舉個(gè)例子,希望對初學(xué)者有所幫助。

原問題見:http://community.csdn.net/EXPert/topic/3886/3886989.xml?temp=.3527033

這類問題通常是為了利用原有Server或者Server不能做修改(通常是c/c++)造成。

比如Server端只接收一個(gè)結(jié)構(gòu)Employee,定義如下:

struct UserInfo {
char UserName[20];
int UserId;
};
struct Employee {
UserInfo user;
float salary;
};
當(dāng)然也可以定義為

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


java client 測試源碼(為說明問題,假設(shè)struct字節(jié)對齊,sizeof(Employee)=28)

import java.net.*;

/**
* 與C語言通信(java做Client,c/c++做Server,傳送一個(gè)結(jié)構(gòu))
* @author kingfish
* @version 1.0
*/
class Employee {
PRivate byte[] buf = new byte[28]; //為說明問題,定死大小,事件中可以靈活處理

/**
* 將int轉(zhuǎn)為低字節(jié)在前,高字節(jié)在后的byte數(shù)組
*/
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轉(zhuǎn)為低字節(jié)在前,高字節(jié)在后的byte數(shù)組
*/
private static byte[] toLH(float f) {
return toLH(Float.floatToRawIntBits(f));
}

/**
* 構(gòu)造并轉(zhuǎn)換
*/
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);
}

/**
* 返回要發(fā)送的數(shù)組
*/
public byte[] getBuf() {
return buf;
}

/**
* 發(fā)送測試
*/
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


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 乌审旗| 汉中市| 青冈县| 中宁县| 广州市| 龙川县| 韩城市| 蓬溪县| 武邑县| 太原市| 和龙市| 涪陵区| 搜索| 霍林郭勒市| 上虞市| 鄄城县| 洞口县| 轮台县| 横山县| 芦山县| 开江县| 濉溪县| 囊谦县| 濮阳县| 浮山县| 阳江市| 吐鲁番市| 西畴县| 淮北市| 神农架林区| 桑植县| 彰化县| 青浦区| 河津市| 名山县| 津市市| 巴林左旗| 通榆县| 哈巴河县| 四川省| 五常市|