Added Crc32 validation instance for Java custom protocol Packet encapsulation, javacrc32

Source: Internet
Author: User
Tags crc32

Added Crc32 validation instance for Java custom protocol Packet encapsulation, javacrc32

The demo just finished directly enters the topic, starts two threads, simulates the Socket server and client communication, and encapsulates the data to send packets in the specified format.

Code:

Import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import java.net. inetAddress; import java.net. serverSocket; import java.net. socket; import java.net. unknownHostException;/*** Created by SiKang on 2016/4/29. */public class CustomData {public static void main (String args []) {// server Thread new Thread (new Runnable () {@ Override public void run () {try {// enable server Socket ServerSoc Ket server = new ServerSocket (9000); // wait for the client to connect to Socket socket = server. accept (); InputStream inputStream = socket. getInputStream (); // obtain the first two bytes as the Packet Length byte [] lenBytes = new byte [2]; inputStream. read (lenBytes); short length = bytesToShort (lenBytes); System. out. println ("length:" + length); // then obtain the next four bytes crc32 check code byte [] crc = new byte [4]; inputStream. read (crc); int crc32 = bytesToInt (crc); // obtain the remaining field v Er, cmd, data byte [] bytes = new byte [length-2-4]; inputStream. read (bytes); // obtain the new Crc32 verification code based on the obtained bytes to verify whether the data is complete (you can read one fewer bytes to see if it can pass) if (crc32 = getCRC32 (bytes) {System. out. println ("Crc32 Right! ");} Else {System. out. println (" Crc32 Error! "); Return;} // retrieve ver cmd int ver = Integer. parseInt (byteToHex (bytes [0]), 16); int cmd = Integer. parseInt (byteToHex (bytes [1]), 16); // check whether the ver sends 0x05 if (ver = 0x05) {System. out. println ("ver: 0x05");} // whether the cmd client sends 0xff if (cmd = 0xff) {System. out. println ("cmd: 0xff");} // get the remaining number of data bytes, and retrieve the data int datalen = length-2-4-1-1; byte [] data = new byte [datalen]; int index = 1; for (int I = 0; I <datalen; I ++) {data [I] = bytes [++ index];} String str = new String (data); System. out. println ("data:" + str); inputStream. close ();} catch (IOException e) {e. printStackTrace ();}}}). start (); // client Thread new Thread (new Runnable () {@ Override public void run () {try {// connect server Socket = new socket (getIpAddress (), 9000); OutputStream outputStream = socket. getOutputStream (); String str = "He Llow World! "; Byte [] data = str. getBytes (); // pack (outputStream, (byte) 0xff, data, data. length); outputStream. flush (); outputStream. close ();} catch (IOException e) {e. printStackTrace ();}}}). start ();}/*** encapsulate and send packets * here, the packet format is {total packet length [2 bytes], Crc32 Verification Code [4 bytes], ver version information [1 byte], cmd Command [1 byte], data content [Several bytes]} */private static void pack (OutputStream out, byte cmd, byte [] data, int len) {try {// first obtain the total length of the message. The number of bytes in the format described above is added to short totalSize = (short) (2 + 4 + 1 + 1 + len); // output packet length out. write (bytes tobyte (totalSize), 0, 2); // The Field byte [] bytes = new byte [1 + 1 + len] to be verified; int index = 0; bytes [index ++] = 0x05; // version number (this is written to an end) bytes [index ++] = cmd; // cmd command // data content for (int I = 0; I <len; I ++) {bytes [index ++] = data [I];} // obtain the crc32 Verification Code of ver, cmd, and data (the Crc32 algorithm is located at the bottom and found on the internet .....) byte [] crc32 = intToBytes (getCRC32 (bytes); // output crc check code out. write (crc32, 0, crc32.length); // output ver, cmd, and data out. write (bytes, 0, bytes. length);} catch (IOException e) {e. printStackTrace () ;}}/*** get local IP */private static String getIpAddress () throws UnknownHostException {InetAddress address = InetAddress. getLocalHost (); return address. getHostAddress ();}/*** convert int to byte [] */public static byte [] intToBytes (int value) {byte [] bytes = new byte [4]; bytes [3] = (byte) (value> 24); bytes [2] = (byte) (value> 16); bytes [1] = (byte) (value> 8); bytes [0] = (byte) (value> 0); return bytes ;} /*** convert short to byte [] */public static byte [] bytes tobyte (short value) {byte [] bytes = new byte [2]; bytes [1] = (byte) (value> 8); bytes [0] = (byte) (value> 0); return bytes ;} /*** convert byte to hexadecimal */public static String byteToHex (byte B) {int I = B & 0xFF; return Integer. toHexString (I);}/*** byte [] to int */public static int bytesToInt (byte [] bytes) {return (int) (bytes [3] & 0xff) <24) | (bytes [2] & 0xff) <16) | (bytes [1] & 0xff) <8) | (bytes [0] & 0xff) <0 )));} /*** convert byte [] to short */public static short bytesToShort (byte [] bytes) {return (short) (bytes [1] <8) | bytes [0] & 0xff);}/*** get the CRC32 Verification Code */public static int getCRC32 (byte [] bytes) {int [] table = {0x00000000, 0x77073096, numeric, 0x990951ba, 0x076dc419, numeric, 0x0edb8832, 0x79dcb8a4, numeric, 0x97d2d988, numeric, 0x7eb17cbd, primary, 0x90bf1d91, 0x1db71064, primary, primary, 0x84be41de, primary, 0x83d1_c7, primary, 0x14015c4f, primary, 0x4c69105e, primary, 0xa2677172, primary, primary, 0xd20d85fd, primary, 0xdbbbc9d6, primary, 0x32d86c4, primary, 0x26d930ac, 0x51de003a, primary, 0x56b3c423, 0xcfba9599, salesman, 0x2802b89e, 0x5f058808, clerk, 0x01db7106, 0x98d220bc, 0xefd5102a, clerk, clerk, hour, 0xe10e9818, hour, 0x086d3d2d, 0x91646c97, hour, 0xf262004e, hour, 0x62dd1ddf, 0x15da2d49, values, numbers, 0xa3bc0074, numbers, 0x0000ed9fc, 0xad678846, numbers, 0x000042d73, 0x33031de5, numbers, numbers, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, clerk, 0xb7bd5c3b, 0xc0ba6cad, clerk, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, primary, 0xe40ecf0b, primary, 0x0a00ae27, primary, 0x196c3671, primary, 0x41b76, primary, primary, 0x67dd4acc, primary, primary, 0x17b7be43, primary, 0x38d8c2c4, primary, 0xd80d2133, primary, 0x36034af6, 0x000047a60, 0xdf60efc3, primary, expires, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, expires, 0x5505262f, expires, 0xec63f226, expires, 0x026d930a, 0x9c0906a9, expires, 0x72076785, 0x05005713, expires, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, expires, 0x68ddb3f8, expires, 0x81be16cd, expires, expires, 0x18b74777, expires, 0x11010b5c, expires, 0xf862ae69, expires, 0x3903b3c2, 0xa7672661, expires, 0x4969474d, expires, primary, 0xd9d65adc, 0x40df0b66, primary, 0xcabac28a, primary, primary, 0xbad03605, primary, 0x54de5729, 0x23d967bf, primary, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,}; int crc = 0 xffffffff; for (byte B: bytes) {crc = (crc >>> 8 ^ table [(crc ^ B) & 0xff]);} crc = crc ^ 0 xffffffff; return crc ;}}

Running result:

The above example of Crc32 verification added to the Java custom protocol Packet encapsulation is all the content shared by Alibaba Cloud. I hope you can provide a reference and support for the customer.

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.