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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值