java與c/c++進行socket通訊的一些問題(1)

來源:互聯網
上載者:User

近幾天看到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方法發送,但位元組順序需要改為低在前。
這個問題稍後在討論。

如有任何問題,請指正!

kingfish
2005.3.29

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.