我觉得这篇文章的标题有点言过其实,因为我无法举出一个对我来说简单的例子。
无论如何,这是一个如何使用Netty使服务器对你进行回应的最小的例子:
NettyExample.java:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import java.nio.charset.Charset;
class NettyExample
{
public static void main( String[] args ) throws Exception
{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try
{
new ServerBootstrap()
.group( bossGroup, workerGroup )
.channel( NioServerSocketChannel.class )
.childHandler( new Init() )
.bind( 1337 ).sync().channel().closeFuture().sync();
}
finally
{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}private static class Init extends ChannelInitializer
{
@Override
public void
initChannel( SocketChannel ch ) throws Exception
{
ch.pipeline().addLast( new ShoutyHandler() );
}
}private static class ShoutyHandler extends ChannelInboundHandlerAdapter
{
@Override
public void channelRead( ChannelHandlerContext ctx, Object msg )
{
try
{
Charset utf8 = CharsetUtil.UTF_8;
String in = ( (ByteBuf)msg ).toString( utf8 );
String out = in.toUpperCase();
// Shout!
ctx.writeAndFlush( Unpooled.copiedBuffer( out, utf8 ) );
}
finally
{
ReferenceCountUtil.release( msg );
}
}@Override
public void exceptionCaught(
ChannelHandlerContext ctx, Throwable cause )
{
cause.printStackTrace();
ctx.close();
}
}
}
实际执行有用任务的行用红色突出显示。如果有人知道如何缩短它,请在下面评论。对我来说似乎很多。
要运行这个,请做:
sudo apt-get install openjdk-8-jdk
wget 'http://search.maven.org/remotecontent?filepath=io/netty/netty-all/4.1.5.Final/netty-all-4.1.5.Final.jar -O netty-all-4.1.5.Final.jar'
javac -Werror -cp netty-all-4.1.5.Final.jar:. NettyExample.java &
&
java -cp netty-all-4.1.5.Final.jar:. NettyExample
然后在另一个终端:
echo "Hello, world" | nc localhost 1337
然后观察响应: HELLO, WORLD
与node . js比较
为了便于比较,在Node.js中有一个近似等价:
【使用Netty 4的简单例子详细步骤】shouty.js:
var net = require('net');
var server = net.createServer(
function( socket ) {
socket.setEncoding('utf8');
socket.on(
'data',
function( data ) {
socket.end( data.toUpperCase() );
}
)
}
);
server.listen( 1337, "localhost" );
执行以下运行程序:
sudo apt-get install nodejs-legacy
node shouty.js
然后在另一个终端:
echo "Hello, world" | nc localhost 1337
然后观察响应: HELLO, WORLD
推荐阅读
- 使用Kotlin DSL在Gradle中构建一个全能的Jar
- Essential for development: these websites/tools make you more different!
- Renix修改报文长度——网络测试仪实操
- #聊一聊悟空编辑器#spring框架事务相关知识点Spring框架教程
- #yyds干货盘点#Python爬虫实战,pyecharts模块,Python实现中国地铁数据可视化
- 我以订披萨为例,给女朋友详细讲了Java设计模式的3种工厂模式
- Spock框架Mock对象方法经验总结#yyds干货盘点#
- 逼真,特别逼真的决策树可视化
- Linux之diff命令