`
liujie5354
  • 浏览: 5943 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

netty开发基本步骤

 
阅读更多

Netty的使用虽然非常灵活,但是基本的步骤很固定,像八股文一样。现总结如下:

1. You create a ServerBootstrap instance to bootstrap the server and bind it later.

2. You create and assign the NioEventLoopGroup instances to handle event processing, such as accepting new connections, receiving data, writing data, and so on.

3. You specify the local InetSocketAddress to which the server binds.

4.You set up a childHandler that executes for every accepted connection.

5. After everything is set up, you call the ServerBootstrap.bind() method to bind the server.

 

服务端代码示例:

 

package com.netty.examples.discard;

 

import io.netty.bootstrap.ServerBootstrap;

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.SocketChannel;

import io.netty.channel.socket.nio.NioServerSocketChannel;

import io.netty.handler.logging.LogLevel;

import io.netty.handler.logging.LoggingHandler;

public class DiscardServer {

private int port;

 

public DiscardServer(int port) {

this.port = port;

}

 

public void run() throws Exception {

EventLoopGroup bossGroup = new NioEventLoopGroup();

EventLoopGroup workerGroup = new NioEventLoopGroup();

 

try {

ServerBootstrap b = new ServerBootstrap();

b.group(bossGroup, workerGroup)

.channel(NioServerSocketChannel.class)

.handler(new LoggingHandler(LogLevel.INFO))

.childHandler(new ChannelInitializer<SocketChannel>() {

@Override

public void initChannel(SocketChannel ch)

throws Exception {

ch.pipeline().addLast(

new DiscardServerHandler());

}

}).option(ChannelOption.SO_BACKLOG, 128)

.childOption(ChannelOption.SO_KEEPALIVE, true);

 

// Bind and start to accept incoming connections.

ChannelFuture f = b.bind(port).sync();

 

// Wait until the server socket is closed.

// In this example, this does not happen, but you can do that to

// gracefully

// shut down your server.

f.channel().closeFuture().sync();

} finally {

workerGroup.shutdownGracefully();

bossGroup.shutdownGracefully();

}

}

 

public static void main(String[] args) throws Exception{

int port;

 

if (args.length > 0) {

port = Integer.parseInt(args[0]);

} else {

port = 8080;

}

 

new DiscardServer(port).run();

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics