DiscardServer.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.discard;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Discards any incoming data.
* 丢弃服务协议,会忽略所有接收数据的协议
*/
public class DiscardServer {
private final int port;//端口
public DiscardServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();//老板线程
EventLoopGroup workerGroup = new NioEventLoopGroup();//员工线程
try {
//创建一个ServerBootstrap实例 ,ServerBootstrap是Netty服务端的启动辅助类,它提供了一系列的方法用于设置服务端启动相关的参数
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
//业务处理
ch.pipeline().addLast(new DiscardServerHandler());
}
});
// 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
//丢弃服务协议,什么都不会做
System.err.println("--------丢弃服务协议--------------");
// 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 = 8088;//运行出错,可能是端口被占用
}
new DiscardServer(port).run();//启动丢弃服务协议
}
}
DiscardServerHandler.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.discard;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Handles a server-side channel.
*/
public class DiscardServerHandler extends SimpleChannelInboundHandler<Object> {
//日志
private static final Logger logger = Logger.getLogger(DiscardServerHandler.class.getName());
@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
// discard
logger.info("---------消息接收器---------------");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
// Close the connection when an exception is raised.
//当出现异常的时候,会关闭连接
logger.log(
Level.WARNING,
"Unexpected exception from downstream.",
cause);
logger.info("-------出现异常,关闭连接-------------");
ctx.close();
}
}
下面是改进过的DiscardServerHandler.java,会相应telnet客户端
在telnet 里输入什么就在服务端控制台输出什么(单字节输出)
package com.netty.demo.discard;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Handles a server-side channel.
*/
public class DiscardServerHandler extends SimpleChannelInboundHandler<Object> {
//日志
private static final Logger logger = Logger.getLogger(DiscardServerHandler.class.getName());
@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
// discard
//自己改动过的,官网例子的这个方法没有任何东西的
logger.info("---------消息接收器---------------");
ByteBuf in=(ByteBuf) msg;
try {
while(in.isReadable()){
System.out.println("--yy--"+(char)in.readByte());
System.out.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
/**
* 在netty5.0版本,不需要释放资源,框架已经自动帮我们释放,
* 如果再加ReferenceCountUtil.release(msg)这句代码,运行就回报错
*/
//ReferenceCountUtil.release(msg);
e.printStackTrace();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
// Close the connection when an exception is raised.
//当出现异常的时候,会关闭连接
logger.log(
Level.WARNING,
"Unexpected exception from downstream.",
cause);
logger.info("-------出现异常,关闭连接-------------");
ctx.close();
}
}
运行效果图: