Java TCP/IP socket programming (5)

Source: Internet
Author: User
3.1 Information encoding
3.1.1 basic integer

TCP and UDP sockets enable us to send and receive byte sequences (arrays) with a range of 0 ~ An integer between 255.

Next we will consider sending a byte integer, a short integer, an int integer, and a long integer, the four types are marked with 1, 2, 4, and 8 bytes in sequence in Java.

1. The sending sequence can be sent from low to high (little-Endian), or from high to low (big-Endian ).

Consider the factory integer 123456787654321l, its 16 forbidden form is 0x0000704885f926b

1. If you use little-Endian to transmit this integer sequentially, the decimal numeric sequence of the bytes is:


If you use big-Endian to transmit this integer sequentially, the decimal numeric sequence of the byte is:


For any multi-byte integer, the sender and receiver must agree on the Transmission sequence used.

2. the sender and receiver should also reach a consensus on whether the sent value is signed or unsigned. The four basic integer types in Java are signed.

The following code demonstrates the sending and receiving integers.

Package COM. suifeng. tcpip. chapter3;/*** sending and receiving of basic integer (analog) ** @ author administrator **/public class bruteforcecoding {// parameter to be transmitted Private Static final byte byteval = 101; Private Static final short implements Vale = 10001; private Static final int intval = 100000001; Private Static final long longval = 000000000001l; // The number of digits occupied by each type: Private Static final int bsize = byte. size/byte. size; Private Static final int ssize = short. size/byte. size; Private Static final int isize = integer. size/byte. size; Private Static final int lsize = long. size/byte. size; // Private Final Static int bytemask = 0xff; /*** print the binary data to be transmitted ** @ Param barray * binary array * @ return */public static string bytearray2decimalstring (byte [] barray) {stringbuilder rbtn = new stringbuilder (256); For (byte B: barray) {rbtn. append (B & bytemask ). append ("");} return rbtn. tostring ();} /*** convert the integer to be sent into a binary array ** @ Param DST * destination binary array * @ Param Val * integer to be transferred * @ Param offset * displacement * @ Param size * bytes occupied * @ return */public static int encodeintbigendian (byte [] DST, long Val, int offset, int size) {for (INT I = 0; I <size; I ++) {DST [offset ++] = (byte) (Val> (size-I-1) * byte. size) ;}return offset ;} /*** parse the encoded data ** @ Param Val * the encrypted binary array * @ Param offset * displacement * @ Param size * @ return */public static long decodeintbigendian (byte [] Val, int offset, int size) {long rbtn = 0; For (INT I = 0; I <size; I ++) {rbtn = (rbtn <byte. size) | (long) Val [Offset + I] & bytemask);} return rbtn;} public static void main (string [] ARGs) {byte [] Message = new byte [bsize + ssize + isize + lsize]; // byte type int offset = encodeintbigendian (message, byteval, 0, bsize ); // short type offset = encodeintbigendian (message, invalid Vale, offset, ssize); // int type offset = encodeintbigendian (message, intval, offset, isize ); // long type offset = encodeintbigendian (message, longval, offset, lsize); system. out. println ("encode message:" + bytearray2decimalstring (Message); // parse the encrypted data offset = 0; // parse bytelong value = decodeintbigendian (message, offset, bsize ); system. out. println ("byte value =" + value); // parse shortoffset + = bsize; value = decodeintbigendian (message, offset, ssize); system. out. println ("Short value =" + value); // parse into ffset + = ssize; value = decodeintbigendian (message, offset, isize); system. out. println ("int value =" + value); // parse longoffset + = isize; value = decodeintbigendian (message, offset, lsize); system. out. println ("long value =" + value );}}

The execution result is as follows:

As shown in, a byte sequence is generated during running.


There are also one way to use the binary read/write operations provided by Java.

Package COM. suifeng. tcpip. chapter3; import Java. io. bytearrayinputstream; import Java. io. bytearrayoutputstream; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. ioexception;/*** sending and receiving of basic integer (analog) ** @ author administrator **/public class bruteforcecoding2 {// parameter to be transmitted Private Static final byte byteval = 101; Private Static final short shortval = 10001; Private Static final int Val = 100000001; Private Static final long longval = 000000000001l; public static void main (string [] ARGs) {byte [] MSG = NULL; bytearrayoutputstream Buf = new bytearrayoutputstream (); dataoutputstream out = new dataoutputstream (BUF); system. out. println ("data to be sent:"); system. out. println ("byte value =" + byteval); system. out. println ("Short value =" + shortval); system. out. println ("int value =" + intval); system. out. prin TLN ("long value =" + longval); try {out. writebyte (byteval); out. writeshort (shortval); out. writeint (intval); out. writelong (longval); out. flush (); MSG = Buf. tobytearray ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} finally {try {If (BUF! = NULL) {Buf. Close ();} If (OUT! = NULL) {Buf. close () ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}} system. out. println (); bytearrayinputstream BAIS = new bytearrayinputstream (MSG); datainputstream Dis = new datainputstream (BAIS); try {system. out. println ("received data:"); system. out. println ("byte value =" + dis. readbyte (); system. out. println ("Short value =" + dis. readshort (); system. out. println ("int value =" + dis. readint (); system. out. println ("long value =" + dis. readlong ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}


The execution result is as follows:

3.1.2 string and text

You can call the getbyte method of string to return an array of characters that encode the string instance based on the default Character Set of the platform. To ensure that a string is encoded according to a specific character set, you only need to pass the name of the character set to the getbytes method. The returned array contains the string of the specified character set.

The sender and receiver must reach a consensus on the string representation method.

3.1.3 bitwise operation: Boolean Encoding

Bitmap is a very compact way to encode Boolean information. The main idea of bitmap is that each bit in the bitmap can represent a Boolean code, usually 0 indicates false, and 1 indicates true. To manipulate bitmap, you can consider using a mask. one or more of these bits are set to 1, and others are cleared.

The operations for bitmap are as follows:

Package COM. suifeng. tcpip. chapter3;/*** bitmap and mask operations * @ author suifeng **/public class bitmaptest {private final static int bit2 = (1 <2 ); // 0000 0100 private final static int bit3 = (1 <3); // 0000 1000 private final static int bit5 = (1 <5 ); // 0010 0000 private final static int bit7 = 0x80; // 0100 0000 0000 private final static int bit2_and_bit3 = 12; // 0110 public static void main (string [] ARGs) {In T bitmap = 1234567; system. out. println ("set the fifth position in bitmap to 1"); // set the fifth position in bitmap to 1 bitmap | = bit5; system. out. println ("the fifth digit is 1:" + (Bitmap & bit5) & bit5 )! = 0); system. out. println (); system. out. println ("set the seventh position in bitmap to 0"); // set the seventh position in bitmap to 1 and obtain the bit7 complement code, then bitmap and bitmap ~ Bit7; system. out. println ("Whether the seventh digit is 1:" + (Bitmap & bit7) & bit7) = 0); system. out. println (); system. out. println ("set the second, third, and fifth positions in bitmap to 0"); // set bitmap 2nd, 3, and 5 to 0 bitmap & = ~ (Bitmap & (bit2_and_bit3 | bit5); system. out. println ("whether the second digit is 0:" + (Bitmap & bit2) & bit2) = 0); system. out. println ("whether the third digit is 0:" + (Bitmap & bit3) & bit3) = 0); system. out. println ("Whether the fifth digit is 0:" + (Bitmap & bit5) & bit5) = 0 ));}}

The execution result is as follows:


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.