Serialization of objects in Netty, deserialization

Source: Internet
Author: User
Tags int size serialization

Previously written Nettydemmo are passed strings, while in real use we are all objects, and then write serialization methods for serialization and serialization, in the Netty for serialization and serialization of the corresponding interface, and Netty also support a lot of serialization methods, But here's how to implement Java serialization first.


First, Java serialization method

Package Com.decode;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;

Import Java.io.ObjectOutputStream;
Import Io.netty.buffer.ByteBuf;

Import io.netty.buffer.Unpooled; /** * Java Serialization tool * * @author WHD * @date November 6, 2017 morning 9:24:35 * * public class Utils {public byte[] encodes (Object
		obj) throws IOException {Bytearrayoutputstream out = new Bytearrayoutputstream ();
		ObjectOutputStream oos = new ObjectOutputStream (out);
		Oos.writeobject (obj);
		Oos.flush ();
		Oos.close ();
		byte[] bytes = Out.tobytearray ();
	return bytes; } public Object decode (byte[] bytes) throws IOException, ClassNotFoundException {//object back serialization Bytearrayinputstream in
		= new Bytearrayinputstream (bytes);
		ObjectInputStream inn = new ObjectInputStream (in);
		Object obj = Inn.readobject ();
	return obj;
		/** * Byte to buf * * @param bytes * * @return/public bytebuf getbuffrombyte (byte[] bytes) {Bytebuf buf = unpooled.copiedbuffer (bytes);
	return buf; /** * BUF to BYTE * * @param buf * * @return/public byte[] Getbytefrombuf (bytebuf buf) {int size = BUF
		. Readablebytes ();
		byte[] bytes = new Byte[size];
		Buf.readbytes (bytes);
	return bytes;
 }
}


Second, the serialization provided in the Netty, the return serialization interface

1, encoder (code)

Package com.rpc;

Import Com.decode.Utils;

Import Io.netty.buffer.ByteBuf;
Import Io.netty.channel.ChannelHandlerContext;
Import Io.netty.handler.codec.MessageToByteEncoder;

Code in/** * Netty * * 
 @author WHD
 * @date December 3, 2017 pm 7:43:23 * * Public
Class Encoder extends messagetobyteencoder<object> {
	/**
	 * We know that the interaction of messages in the computer is byte but encapsulated in Netty so the basic delivery type in Netty is Bytebuf
	 *
	/@Override protected void encode (Channelhandlercontext ctx, Object in, bytebuf out) throws Exception {
		Utils util = new Utils ();
		byte[] bytes = Util.encodes (in);
		Out.writebytes (bytes);
	}



2, Decoder (decoding)

Package com.rpc;

Import java.util.List;

Import Com.decode.Utils;

Import Io.netty.buffer.ByteBuf;
Import Io.netty.channel.ChannelHandlerContext;
Import Io.netty.handler.codec.ByteToMessageDecoder;

/** * Decode * * 
 @author WHD
 * @date November 6, 2017 pm 1:56:45/public
class Decoder extends Bytetomessagedecoder {
	private static final int LENGTH = 4;

	/**
	 * Decoding newsletters in the parameter is Bytebuf is the basic unit of Netty, and the outgoing is the decoded object
	 * * *
	@Override
	protected void decode ( Channelhandlercontext arg0, Bytebuf in, list<object> out) throws Exception {Utils util
		= new Utils ();
		int size = In.readablebytes ();
		The size is judged to be the problem of TCP's sticky packets, and this is followed by a separate learning
		if (Size > Decoder.length) {
			byte[] bytes = Util.getbytefrombuf (in);
			Object info = util.decode (bytes);
			Out.add (info);}}


Note that the 4.+ version of Netty and the 5.0 version of the difference is still a little large so in the use of the time to pay attention to, here is the use of the Netty version 5.0 ...


Ok so the encoding and decoding OK, in the Netty encoding and decoding is very simple, said before the Netty on the channel of the message processing is a chain is also channelpipeline, So when we implement the codec and then use it directly into the Channelpipeline, OK:

Client Channelpipeline:

Private class Initializerchannel extends Channelinitializer<socketchannel> {
		@Override
		protected void Initchannel (Socketchannel ch) throws Exception {Channelpipeline Pipeline
			= Ch.pipeline ();
			Pipeline.addlast (New encoder ());
			Pipeline.addlast (New Decoder ());
			Pipeline.addlast (New ClientHandler ());
		}
	

Service-side channelpipeline:

Private class Childchannelhandler extends Channelinitializer<socketchannel> {
		@Override
		protected void Initchannel (Socketchannel ch) throws Exception {
			channelpipeline cp = Ch.pipeline ();
			Cp.addlast (New Decoder ());
			Cp.addlast (New encoder ());
			Cp.addlast (New Serverhandler ());
		}
	
Encoding and decoding process:

The client application writes object to the Netty channel, and then the Channelpipeline chain follows the configuration of converting object to byte to the TCP cache, and then the network spreads

The server-side reads the byte stream from the server-side TCP cache, and then enters Serverapplication from the TCP cache. The first thing to do when entering Netty Channelpipeline is to decode byte to object. Using the decoder we have configured in the pipeline so that we get the decoded object in the Channelread () method, which can be directly converted to the object we need to handle, which is convenient.

It is also the same process from server-side response messages to clients.

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.