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);  
              
            Length += temp_length;  
            Send(String.valueOf(Length),false);  
       }  
    return _bytestream.toByteArray();  
      
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM