Netty4 and protocol buffer combination simple tutorial, netty4buffer

Source: Internet
Author: User

Netty4 and protocol buffer combination simple tutorial, netty4buffer

Binary communication is usually used between various projects, which requires a small bandwidth and fast processing speed ~

Thanks to Trustin Lee, the author of netty, for letting netty naturally support protocol buffer.

This example uses netty4 + protobuf-2.5.0, run in win7, and assuming jdk and maven have been installed.

1. Download and decompress protoc-2.5.0-win32.zipand protobuf-2.5.0.zip

2 To protobuf-2.5.0.zip installation directory under the protobuf-2.5.0 \ java, execute the maven command: mvn package jar: jar, will generate target \ protobuf-java-2.5.0.jar

3. Define the proto file test. proto:

Package domain;

Option java_package = "com. server. domain ";

Message TestPro {
Required string test = 1;
}

4. Copy 2nd jar packages to the java file storage directory and run the following command to generate a java file:

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

5. Put the generated protobuf-java-2.5.0.jar and the jar package of netty4 into the classpath of the project, and put the 4th java files generated in the corresponding path of the project.

6. Write Server code

1) Compile the 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) register the service and bind the 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. Compile Client code

1) define the handler class of the Client:

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 a connection from the Client to the Server

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 ();

// Enter in the console
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, click it.

Recommended other reference Tutorials: protocol and netty combination of information http://blog.csdn.net/goldenfish1919/article/details/6719276


[Python] How to Use protocol buffer in python

Search for protocol buffer on code.google.com, download it to your local computer, decompress the package, and execute the following commands:
./Configuremakemake checkmake install
The last step involves permissions and sudo may be required.
2. Define a proto File
The following is a simple example. To use proto, you must first define a proto file and a people. proto file. The content is as follows:
Message people {
Optional string name = 1;
Optional int32 height = 2;} 3. Generate a python available py file
The command is as follows:
Protoc-I =./-- python_out =./people. proto
Here,-I is the source Path, -- python_out indicates the generated path of the corresponding python library, and then the corresponding proto file. Of course, pb also supports c ++ and java, just modify -- python_out.
The corresponding lele_pb2.py file is displayed. After the import, you can use it. The prompt ImportError: No module named google should be displayed. protobuf. This is because the corresponding library path cannot be found. Go to the pb path you downloaded, find the python path, and run sudo python setup. py install. After execution, run sudo python setup. py test check whether the installation is successful. If the last prompt is displayed
----------------------------------------------------------------------
Ran 193 tests in 0.327sOK is installed successfully. Then, import the corresponding pb2.py file to use it.
Iv. Simple import example
A simple debugging example is provided:
Import people_pbs
PbFirstPeople = people_pb2.people ()
PbFirstPeople. name = joey
PbFirstPeople. height = 160
Print pbFirstPeople
Output result: name: joey

Error LNK2019 error solved

I have encountered such a problem,
Now, ghost 2 is vulnerable to viruses, and it is difficult to clear the virus. However, ghost 2 exists in 360. You can search for "360 ghost 2 exclusive removal" on Baidu to download and decompress it, and then double-click the fixmbr.exe program, if no prompt is displayed, it means that you do not have the virus. If a prompt is displayed, it indicates that you are infected with the ghost 2 virus. Click OK as prompted]
Use the 360 first aid kit to fix the system!
I reinstalled the computer, formatted the hard disk, and then there was no poison.
Www.winbaicai.com/help_435.html
This is a USB flash drive reinstallation 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.