这些天需要用java做一个简单的合成类小游戏,准备使用spring-websoket+stomp实现的。但之前做过一个,同时也想尝试一下netty的魅力。
1.初始化ServerBootstrap,创建netty服务入口
@Component
public class WSServer {
private static class SingletionWSServer {
static final WSServer instance = new WSServer();
}
public static WSServer getInstance() {
return SingletionWSServer.instance;
}
private EventLoopGroup mainGroup;
private EventLoopGroup subGroup;
private ServerBootstrap server;
private ChannelFuture future;
public WSServer() {
mainGroup = new NioEventLoopGroup();
subGroup = new NioEventLoopGroup();
server = new ServerBootstrap();
server.group(mainGroup, subGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new WSServerInitialzer());
}
public void start() {
this.future = server.bind(26387);
System.err.println("started netty websocket server...");
}
}
2.初始化channel,处理消息
public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
//使用http编解码
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(1024*64));
//心跳检测,读空闲30s触发,写空闲30s,都空闲60s
pipeline.addLast(new IdleStateHandler(30, 30, 60));
pipeline.addLast(new HeartBeatHandler());
//websocket访问路由 /ws
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
//定义handler处理请求
pipeline.addLast