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

來源:互聯網
上載者:User

第一部分請見http://blog.csdn.net/kingfish/archive/2005/03/29/333635.aspx

本部分提出另外一種做法, 供參考。

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
2005.3.30

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.