Some problems in the socket communication between Java and C + + (2)

Source: Internet
Author: User
Tags return socket
c++| question This part proposes another method for the reference.


Import java.net.*;
Import java.io.*;

/**
* Communicate with C language (Java do client,c/c++ do server, send a structure)
* @author Kingfish
* @version 1.0
*/
public class Employee2 {
private String name;
private int id;
private float salary;

/**
* Convert int to low byte in front, high byte in the back of 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;
}

/**
* Convert float to low byte in front, high byte after int
*/
private static int Tolh (float f) {
Return Tolh (Float.floattorawintbits (f));
}

/**
* Construct and convert
*/
Public Employee2 (String name, int id, float salary) {
THIS.name = name;
This.id = ID;
This.salary = salary;
}

/**
* Get name, fixed long byte array
*/
Public byte[] GetName () {
Byte[] B = new BYTE[20];
System.arraycopy (Name.getbytes (), 0, B, 0, name.getbytes (). length);
return b;
}

/**
* Get number (low byte in front)
*/
public int getId () {
return Tolh (ID);
}

/**
* Get paid (low byte in front)
*/
public int getsalary () {
return Tolh (Salary);
}

/**
* Send Test
*/
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

-----------------------------------------------------------------------------------------------------

If you have any questions, please correct me.

Kingfish



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.