-
服务端
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;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
public class Server {
public static void main(String[] args) {
EventLoopGroup bossGroup=new NioEventLoopGroup();
EventLoopGroup workerGroup=new NioEventLoopGroup();
ServerBootstrap serverBootstrap=new ServerBootstrap()
.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//1 加入http的编解码器
ch.pipeline().addLast(new HttpServerCodec());
//2 以块方式写的处理器
ch.pipeline().addLast(new ChunkedWriteHandler());
//3.1 http使用分段传输方式,此处理器用来分段聚合(当发送大量的数据的时候可能出现多次http请求)
//3.2 用POST方式请求服务器的时候,对应的参数信息是保存在请求体中的,如果只是单纯的用HttpServerCodec是无法完全的解析Http POST请求的
// 因为HttpServerCodec只能获取uri中参数,所以需要加上HttpObjectAggregator
//3.3 把消息分发给如下处理器进行处理
// WebSocketFrame (io.netty.handler.codec.http.websocketx)
// BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx)
// TextWebSocketFrame (io.netty.handler.codec.http.websocketx)
// PongWebSocketFrame (io.netty.handler.codec.http.websocketx)
// ContinuationWebSocketFrame (io.netty.handler.codec.http.websocketx)
// PingWebSocketFrame (io.netty.handler.codec.http.websocketx)
// CloseWebSocketFrame (io.netty.handler.codec.http.websocketx)
ch.pipeline().addLast(new HttpObjectAggregator(8192));
//4 将http协议升级成websocket协议,保持长连接
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/hello"));
//5 处理TextWebSocketFrame相关的业务逻辑
ch.pipeline().addLast(new MyTextWebSocketFrame());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(9999);
channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
if(future.isSuccess()){
System.out.println("ok");
}else {
System.out.println("no");
}
}
});
}
}
-
处理器
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import java.net.SocketAddress;
public class MyTextWebSocketFrame extends SimpleChannelInboundHandler<TextWebSocketFrame> {
//1 当客户端连接时触发
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerAdded,加入连接");
}
//当客户端连接断开时触发
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved,断开连接");
}
//2 当和worker线程组中的某一个线程的selector建立连接时触发(channel注册到EventLoop)
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelRegistered,注册成功");
}
//当和worker线程组中的某一个线程的selector断开连接时触发(channel从EventLoop取消注册)
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelUnregistered,取消注册");
}
//3 当通道处于可活动状态后触发(channel激活的时候)
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
SocketAddress remoteAddress = ctx.channel().remoteAddress();
System.out.println(remoteAddress+"上线了");
}
//当前channel不活跃的时候,也就是当前channel到了它生命周期末
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
SocketAddress remoteAddress = ctx.channel().remoteAddress();
System.out.println(remoteAddress+"下线了");
}
//4 当前channel从远端读取到数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
SocketAddress remoteAddress = ctx.channel().remoteAddress();
System.out.println(remoteAddress+"收到消息:"+msg.text());
ctx.channel().write(new TextWebSocketFrame("hello"));
}
//5 channel read消费完读取的数据的时候被触发
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
SocketAddress remoteAddress = ctx.channel().remoteAddress();
System.out.println(remoteAddress+"消息读取完毕");
ctx.channel().flush();
}
//channel的写状态变化的时候触发
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelWritabilityChanged");
}
//当通道发生异常时触发
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
SocketAddress remoteAddress = ctx.channel().remoteAddress();
System.out.println(remoteAddress+"连接出现异常");
//关闭通道
ctx.channel().close();
}
//用户事件触发的时候(如空闲检测)
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
System.out.println("MyTextWebSocketFrame userEventTriggered:" + evt);
}
}