java与c/c++进行socket通信
比如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方法发送,但字节顺序需要改为低在前。
这个问题稍后在讨论。
如有任何问题,请指正!
对于java端的接收有些问题,
我列出我们以前的接收函数:
public String Receive() throws IOException
{
byte[] buffer = new byte[8];//byte[1024]
int count = 0;
ips=_Socket.getInputStream();
ios=new DataInputStream(ips);
if (listMsg.size() == 0)
{
count=ios.read(buffer, 0, buffer.length);//获取字符数组和其长度
String str=new String(buffer,0,count,"gb2312");//转换成字符串
String[] strs=str.split("//|");
for (int i = 0; i < strs.length; i++)
{
if (strs[i].toString() != "")
{
listMsg.add(strs[i]);
}
}
str = listMsg.get(0).toString().trim();
listMsg.remove(0);
buffer = null;
return str;
}
else
{
String str = listMsg.get(0).toString().trim();
listMsg.remove(0);
buffer = null;
return str;
}
}
接收流函数:
/*
* 接收流,注意流的大小,避免溢出
* linc
* 2010-9-13
*/
public byte[] ReceiveStream() throws Exception
{
String str = Receive();
int num = Integer.parseInt(str);//获得流的长度
Send("0|",false);
ByteArrayOutputStream _bytestream=new ByteArrayOutputStream();
InputStream _InputStream=_Socket.getInputStream();
int Length=0;
byte[] buffer = new byte[1024];
while (Length < num)
{
int temp_length = buffer.length;//1024
if ((num - Length) < temp_length)
{
temp_length = num - Length;
}
_InputStream.read(buffer, 0, temp_length);
_bytestream.write(buffer, 0, temp_length);
 
补充:软件开发 , Java ,