-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNettyIO.java
More file actions
92 lines (66 loc) · 2.62 KB
/
NettyIO.java
File metadata and controls
92 lines (66 loc) · 2.62 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.zs.system.io;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class NettyIO {
public static void main(String[] args) {
NioEventLoopGroup boss = new NioEventLoopGroup(2);
NioEventLoopGroup worker = new NioEventLoopGroup(2);
ServerBootstrap boot = new ServerBootstrap();
try {
boot.group(boss, worker)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,false)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new MyInbound());
p.addLast(new MyInbound());
p.addLast(new MyInbound());
p.addLast(new MyInbound());
p.addLast(new MyInbound());
}
})
.bind(9999)
.sync() //阻塞当前线程到服务启动起来
.channel()
.closeFuture()
.sync(); //阻塞当前线程到服务停止
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyInbound extends ChannelInboundHandlerAdapter{
// @Override
// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// System.out.println(msg);
// ctx.write(msg);
// }
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
int size = buf.writerIndex();
byte[] data = new byte[size];
buf.getBytes(0,data);
String dd = new String(data);
String[] strs = dd.split("\n");
for (String str : strs) {
System.out.print("触发的命令:"+str+"...");
}
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("客户端断开了连接");
super.channelUnregistered(ctx);
}
}