package com.xcong.excoin.netty.server;
|
|
import com.xcong.excoin.netty.ChatServer;
|
import com.xcong.excoin.netty.initalizer.WebSocketServerInitializer;
|
import io.netty.bootstrap.ServerBootstrap;
|
import io.netty.channel.ChannelFuture;
|
import io.netty.channel.EventLoopGroup;
|
import io.netty.channel.nio.NioEventLoopGroup;
|
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.stereotype.Component;
|
|
/**
|
* @author wzy
|
* @date 2019-05-06
|
*/
|
@Slf4j
|
@Component("webSocketServer")
|
public class WebSocketServer implements ChatServer {
|
|
|
private EventLoopGroup boss = new NioEventLoopGroup();
|
private EventLoopGroup work = new NioEventLoopGroup();
|
|
private ChannelFuture channelFuture;
|
|
@Autowired
|
private WebSocketServerInitializer webSocketServerInitializer;
|
|
@Override
|
public void start() throws Exception {
|
log.info("[websocket服务器启动]");
|
try {
|
ServerBootstrap b = new ServerBootstrap();
|
b.group(boss, work)
|
.channel(NioServerSocketChannel.class)
|
.childHandler(webSocketServerInitializer);
|
|
channelFuture = b.bind(9999).sync();
|
|
log.info("[websocket服务器启动完成]-->{}", channelFuture.channel().localAddress());
|
} finally {
|
Runtime.getRuntime().addShutdownHook(new Thread() {
|
@Override
|
public void run() {
|
shutdown();
|
}
|
});
|
}
|
}
|
|
@Override
|
public void shutdown() {
|
if (channelFuture != null) {
|
channelFuture.channel().close().syncUninterruptibly();
|
}
|
|
if (boss != null) {
|
boss.shutdownGracefully();
|
}
|
|
if (work != null) {
|
work.shutdownGracefully();
|
}
|
}
|
|
}
|