TcpServer.java
1.8 KB
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
package com.zhonglai.socket.html;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
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.net.InetSocketAddress;
/**
* 基于JAVA AIO的,面向TCP/IP的,非阻塞式Sockect服务器框架类
*
* @author zer0
* @version 1.0
* @date 2015-2-15
*/
public class TcpServer {
private volatile Integer port;//服务器端口
private Channel channel;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private ChannelInitializer channelInitializer;
public TcpServer(Integer port, ChannelInitializer channelInitializer){
this.port = port;
this.channelInitializer = channelInitializer;
}
/**
* 启动服务器
*
* @author zer0
* @version 1.0
* @date 2015-2-19
*/
public ChannelFuture startServer(){
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(channelInitializer)
.handler(new LoggingHandler(LogLevel.INFO))
.option(ChannelOption.SO_BACKLOG, 128); // 设置tcp协议的请求等待队列
try {
ChannelFuture future = bootstrap.bind(new InetSocketAddress(port)).sync();
channel = future.channel();
System.out.println("服务器已启动,端口:" + port);
return future;
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
public void destory(){
if (channel != null) {
channel.close();
}
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}