Netty4 and protocol buffer combined with a simple tutorial

Source: Internet
Author: User

Communication between projects is usually done using binary, small bandwidth, fast processing speed ~

Thanks to Netty author trustin Lee, let Netty naturally support protocol buffer.

This example uses netty4+protobuf-2.5.0, executes under Win7, and assumes that JDK and Maven have been installed.

1. Download and unzip Protoc-2.5.0-win32.zip and Protobuf-2.5.0.zip

2, to protobuf-2.5.0.zip installation directory Protobuf-2.5.0\java, execute MAVEN command: MVN package Jar:jar, will generate Target\protobuf-java-2.5.0.jar

3. Define Proto file Test.proto:

Package domain;

Option Java_package = "Com.server.domain";

Message Testpro {
Required String test = 1;
}

4. Copy the 2nd jar package to the Java file directory and run the following command to generate the Java file:

Protoc-2.5.0-win32.zip installation directory \protoc.exe--java_out=java file directory proto definition file directory \test.proto

5. Put the generated Protobuf-java-2.5.0.jar and Netty4 jar packages into the classpath of the project, and place the Java file generated by the 4th into the corresponding path of the project.

6. Writing server-side code

1), write handler class:

Import Io.netty.channel.ChannelHandlerContext;
Import Io.netty.channel.SimpleChannelInboundHandler;

public class Serverhandler extends Simplechannelinboundhandler<test.testpro> {
@Override
public void channelRead0 (Channelhandlercontext ctx, Test.testpro msg) throws Exception {
SYSTEM.OUT.PRINTLN ("Server:" + "Channelread:" + msg.gettest ());

Test.TestPro.Builder Builder = Test.TestPro.newBuilder ();
Builder.settest ("Received your message!");
Ctx.writeandflush (Builder.build ());
}
}

2), registration service, bound port:

Import Io.netty.bootstrap.ServerBootstrap;
Import Io.netty.channel.Channel;
Import Io.netty.channel.ChannelFuture;
Import Io.netty.channel.ChannelInitializer;
Import io.netty.channel.ChannelOption;
Import Io.netty.channel.EventLoopGroup;
Import Io.netty.channel.nio.NioEventLoopGroup;
Import Io.netty.channel.socket.nio.NioServerSocketChannel;
Import Io.netty.handler.codec.protobuf.ProtobufDecoder;
Import Io.netty.handler.codec.protobuf.ProtobufEncoder;

public class Server {

public static void Main (string[] args) {
Eventloopgroup Bosseventloopgroup = new Nioeventloopgroup ();
Eventloopgroup Workereventloopgroup = new Nioeventloopgroup ();
try {
Serverbootstrap serverbootstrap = new Serverbootstrap ();
Serverbootstrap.group (Bosseventloopgroup, Workereventloopgroup);
Serverbootstrap.channel (Nioserversocketchannel.class);
Serverbootstrap.childhandler (New channelinitializer<channel> () {
@Override
protected void Initchannel (Channel ch) throws Exception {
Ch.pipeline (). AddLast ("encoder", New Protobufencoder ());
Ch.pipeline (). AddLast ("Decoder", New Protobufdecoder (Test.TestPro.getDefaultInstance ()));
Ch.pipeline (). AddLast ("handler", New Serverhandler ());
};
});
Serverbootstrap.childoption (channeloption.so_keepalive, true);
Channelfuture channelfuture = Serverbootstrap.bind (8888). sync ();
Channelfuture.channel (). Closefuture (). sync ();
} catch (Exception e) {
E.printstacktrace ();
} finally {
Bosseventloopgroup.shutdowngracefully ();
Workereventloopgroup.shutdowngracefully ();
}
}
}

7. Writing client-side code

1), define the client side of the handler class:

Import Io.netty.channel.ChannelHandlerContext;
Import Io.netty.channel.SimpleChannelInboundHandler;

public class ClientHandler extends Simplechannelinboundhandler<test.testpro> {

@Override
protected void channelRead0 (Channelhandlercontext ctx, Test.testpro msg) throws Exception {
SYSTEM.OUT.PRINTLN ("Client:" + "Channelread:" + msg.gettest ());
}
}

2), establish client-side to server-side connection

Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;

Import Io.netty.bootstrap.Bootstrap;
Import Io.netty.channel.Channel;
Import Io.netty.channel.ChannelInitializer;
Import Io.netty.channel.EventLoopGroup;
Import Io.netty.channel.nio.NioEventLoopGroup;
Import Io.netty.channel.socket.nio.NioSocketChannel;
Import Io.netty.handler.codec.protobuf.ProtobufDecoder;
Import Io.netty.handler.codec.protobuf.ProtobufEncoder;
Import Io.netty.handler.codec.string.StringDecoder;
Import Io.netty.handler.codec.string.StringEncoder;

public class Client {

public static void Main (string[] args) {
Eventloopgroup Eventloopgroup = new Nioeventloopgroup ();
try {
Bootstrap Bootstrap = new Bootstrap ();
Bootstrap.group (Eventloopgroup);
Bootstrap.channel (Niosocketchannel.class);
Bootstrap.handler (New channelinitializer<channel> () {
@Override
protected void Initchannel (Channel ch) throws Exception {
Ch.pipeline (). AddLast ("encoder", New Protobufencoder ());
Ch.pipeline (). AddLast ("Decoder", New Protobufdecoder (Test.TestPro.getDefaultInstance ()));
Ch.pipeline (). AddLast ("handler", New ClientHandler ());
};
});

Channel ch = bootstrap.connect ("127.0.0.1", 8888). Sync (). Channel ();

Console input
BufferedReader in = new BufferedReader (new InputStreamReader (system.in));
for (;;) {
String line = In.readline ();
if (line = = NULL | | "". Equals (line)) {
Continue
}
Test.TestPro.Builder Builder = Test.TestPro.newBuilder ();
Builder.settest (line);
Ch.writeandflush (Builder.build ());
}
} catch (Exception e) {
E.printstacktrace ();
} finally {
Eventloopgroup.shutdowngracefully ();
}
}
}


Getting Started tutorial, welcome to shoot bricks.

Recommended additional reference Tutorials: protocol and Netty Data http://blog.csdn.net/goldenfish1919/article/details/6719276

Netty4 and protocol buffer combined with a simple tutorial

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.