Some issues for Socket communication in Java and CC ++ (1)

xiaoxiao2021-03-06  18

In recent days, I saw 9CBS asked C / C and Java communication, especially C-unique data structures (such as struct).

Specially based on a question of netizens, I hope to help beginners.

Original problem See: http://community.9cbs.net/expert/topic/3886/3886989.xml? Temp = .3527033

Such problems are usually caused by using the original Server or Server can't make modifications (usually C / C ).

For example, the Server terminal receives only one structure EMPLOYEE, defined as follows:

Struct Userinfo {Char UserName [20]; int userid;}; struct EMPLOYEE {UserInfo User; float salary;}; of course,

Struct Employee {Char Name [20]; int ID; float salary;

Java Client Test Source (for explaining, assume Struct byte alignment, sizeof (employee) = 28)

Import java.net. *;

/ ** * Communication with C language (Java Do Client, C / C Make Server, transfer a structure) * @Author kingfish * @version 1.0 * / class Employee {private byte [] buf = new byte [28]; // To illustrate problems, the size of death can be flexible in the event

/ ** * Byte array of INT to low byte before, high byte after the high byte * / private static byte [] b = new byte [4]; b [0] = (Byte) (N & 0xFF); B [1] = (Byte) (N >> 8 & 0xFF); B [2] = (Byte) (N >> 16 & 0xFF); B [3] = (N >> 24 & 0xFF); return b;}

/ ** * turn float to a low byte in the BYTE array after high byte * / private static byte [] tolh (float f) {returnTBITS (F));}

/ ** * Construct and convert * / 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);

/ ** * Return to the array to send * / public byte [] getBuf () {Return BUF;}

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

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

Of course, it is also possible to send the WriteInt, Writefloat method, but byte order needs to be changed to low. This problem is discussed later.

If there is any problem, please correct it!

Kingfish2005.3.29

转载请注明原文地址:https://www.9cbs.com/read-41071.html

New Post(0)