yanghb
2023-04-20 ef3e346722aeea61bd8a13490bae28bc381b2951
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
69
70
71
72
73
74
75
76
77
78
package com.sinata.zuul.util.applets;
 
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
 
import java.util.Timer;
import java.util.TimerTask;
 
 
/**
 * 即时通讯服务启动类
 * 
 * @date 2016年6月25日
 * @version 1.0
 */
public class NettyServer0 {
 
    /**
     * 延迟启动设置
     * 
     * NettyServer启动方法.
     */
    public void bind() {
        final Thread thread = new Thread(new NettyRunnable());
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                thread.start();
            }
        }, 1000 * 2);
    }
    
    /**
     * 即时通讯服务启动
     * 
     * @date 2016年6月24日
     * @version 1.0
     */
    public class NettyRunnable implements Runnable {
        
        /**
         * 获取即时通讯启动端口 
         */
        @Override
        public void run() {
            System.out.println("===========================Netty端口启动========");
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                //1.创建服务端启动助手
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                //2.设置线程组
                serverBootstrap.group(bossGroup, workerGroup);
                //3.设置参数
                serverBootstrap.channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(LogLevel.DEBUG))
                        .childHandler(new ChildChannelHandler());
                System.out.println("服务端开启等待客户端连接 ... ...");
                //4.启动
                ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
                System.out.println("--Netty服务端启动成功---");
                channelFuture.channel().closeFuture().sync();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }
}