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;

扫描二维码关注公众号,回复: 541409 查看本文章

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

}

}

猜你喜欢

转载自liujie5354.iteye.com/blog/2207589