EchoServer.java
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.netty.demo.echo;
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;
/**
* Echoes back any received data from a client.
*/
public class EchoServer {
private final int port;
public EchoServer(int port) {
this.port = port;
}
public void run() throws Exception {
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup();//老板线程//bossGroup线程池用来接受客户端的连接请求
EventLoopGroup workerGroup = new NioEventLoopGroup();//员工线程 //workerGroup线程池用来处理boss线程池里面的连接的数据
try {
//通过ServerBootStrap对象,来启动服务器
ServerBootstrap b = new ServerBootstrap();
//通过group方法,来绑定EventLoopGroup,EventLoopGroup用来处理SocketChannel和Channel上面的所有时间和IO
b.group(bossGroup, workerGroup);
/*
* 设置并绑定服务端Channel。作为NIO服务端,
* 需要创建ServerSocketChannel,
* Netty对原生的NIO类库进行了封装,
* 对应实现是NioServerSocketChannel。
* 对于用户而言,不需要关心服务端Channel的底层实现细节和工作原理,
* 只需要指定具体使用哪种服务端Channel即可。
* 因此,Netty的ServerBootstrap方法提供了channel方法用于指定服务端Channel的类型。
* Netty通过工厂类,利用反射创建NioServerSocketChannel对象。
* 由于服务端监听端口往往只需要在系统启动时才会调用,因此反射对性能的影响并不大
*/
b.channel(NioServerSocketChannel.class);//设置并绑定服务端Channel,这里绑定NioServerSocketChannel
AbstractBootstrap.option()用来设置ServerSocket的参数,AbstractBootstrap.childOption()用来设置Socket的参数。
b.option(ChannelOption.SO_BACKLOG, 100);//?????
b.handler(new LoggingHandler(LogLevel.INFO));
//最后实例化一个ChannelInitializer
/**
* ChannelInitializer是一个特殊的handler,
* 用来初始化ChannelPipeline里面的handler链。
* 这个特殊的ChannelInitializer在加入到pipeline后,
* 在initChannel调用结束后,自身会被remove掉,从而完成初始化的效果
*/
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
//new LoggingHandler(LogLevel.INFO),
new EchoServerHandler());
}
});
// Start the server.
ChannelFuture f = b.bind(port).sync();
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
//终结所有线程
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port=8088;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8088;
}
System.out.println("启动服务");
new EchoServer(8088).run();//执行echo
}
}
EchoServerHandler.java
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.netty.demo.echo;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Handler implementation for the echo server.
*/
@Sharable
public class EchoServerHandler extends ChannelHandlerAdapter {
private static final Logger logger = Logger.getLogger(
EchoServerHandler.class.getName());
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
/**
* Channel 公路,双向道,分为去路和来路。隐喻为网络连接。
ChannelPipeline,公路管理部门,可以设置收费站,关卡等设施对车辆进行检查。
ByteBuf 车辆。隐喻为网络连接中的数据。
Handler 收费站,关卡;可以对公路上的车辆进行各种处理
*/
msg="wo qu ni ma";
System.out.println("------Handler 收费站,关卡;可以对公路上的车辆进行各种处理----------");
ctx.write(msg);//把消息写入缓冲区
ctx.flush();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//调用ctx.flush();方法把缓冲区的数据强行输出
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
logger.log(Level.WARNING, "Unexpected exception from downstream.", cause);
ctx.close();
}
}