package com.hxzk.util.Netty;
|
|
|
|
import com.hxzk.service.CabinetService;
|
import com.hxzk.service.FaKaService;
|
import com.hxzk.service.PersonService;
|
import io.netty.bootstrap.ServerBootstrap;
|
import io.netty.channel.*;
|
import io.netty.channel.nio.NioEventLoopGroup;
|
import io.netty.channel.socket.SocketChannel;
|
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
import io.netty.handler.codec.string.StringEncoder;
|
import io.netty.handler.timeout.IdleStateHandler;
|
import org.springframework.stereotype.Component;
|
|
import java.util.Stack;
|
import java.util.concurrent.TimeUnit;
|
|
|
@Component
|
public class NettyServer {
|
|
static ChannelFuture cf = null;
|
|
static PersonService personService;
|
static CabinetService cabinetService;
|
|
static FaKaService faKaService;
|
public NettyServer(PersonService personService1,CabinetService cabinetService1,FaKaService faKaService1) {
|
this.personService = personService1;
|
this.cabinetService =cabinetService1;
|
this.faKaService = faKaService1;
|
}
|
|
public NettyServer() {
|
}
|
|
public static void server(int port) {
|
|
System.out.println("开始监听"+port);
|
EventLoopGroup bossGroup = new NioEventLoopGroup();
|
EventLoopGroup workerGroup = new NioEventLoopGroup();
|
|
try {
|
//创建服务器端的启动对象,配置参数
|
ServerBootstrap bootstrap = new ServerBootstrap();
|
|
//使用链式编程来进行设置
|
bootstrap.group(bossGroup, workerGroup)
|
.channel(NioServerSocketChannel.class)
|
.option(ChannelOption.SO_BACKLOG, 1024)
|
.childOption(ChannelOption.SO_KEEPALIVE, true) //设置保持活动连接状态
|
|
|
.childHandler(new ChannelInitializer<SocketChannel>() {// 最后绑定I/O事件的处理类
|
public void initChannel(SocketChannel ch) throws Exception {
|
ChannelPipeline pipeline = ch.pipeline();
|
/**
|
* readerIdleTime 多长时间没有读,就会发送一个心跳检测包检测是否连接
|
* writerIdleTime 多长时间没有写,就会发送一个心跳检测包检测是否连接
|
* allIdleTime 多长时间没有读/写,就会发送一个心跳检测包检测是否连接
|
* */
|
pipeline.addLast("decoder", new StringEncoder());
|
pipeline.addLast("encoder", new StringEncoder());
|
pipeline.addLast(new IdleStateHandler(60, 120, 120, TimeUnit.SECONDS));
|
pipeline.addLast(new NettyServerHandler(personService,cabinetService,faKaService));
|
pipeline.addLast(new GroupChatServerHandler());
|
|
}
|
});
|
|
cf = bootstrap.bind(port).sync();
|
cf.channel().closeFuture().addListener(new ChannelFutureListener() {
|
public void operationComplete(ChannelFuture future) throws Exception {
|
cf.channel().close();
|
}
|
});
|
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
|
|
|
}
|