Helius
2020-07-07 a20a6e0fffacd42495e96016d302ca7532d98778
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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();
        }
    }
 
}