1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix.demo.netty;
19
20 import java.io.File;
21 import java.nio.channels.spi.SelectorProvider;
22 import java.util.concurrent.Executor;
23
24 import org.newsclub.net.unix.AFSocketAddress;
25 import org.newsclub.net.unix.AFUNIXSelectorProvider;
26 import org.newsclub.net.unix.AFUNIXSocketAddress;
27
28 import io.netty.bootstrap.ServerBootstrap;
29 import io.netty.channel.ChannelFuture;
30 import io.netty.channel.ChannelInitializer;
31 import io.netty.channel.ChannelOption;
32 import io.netty.channel.EventLoopGroup;
33 import io.netty.channel.nio.NioEventLoopGroup;
34 import io.netty.channel.socket.SocketChannel;
35 import io.netty.channel.socket.nio.NioServerSocketChannel;
36
37
38
39
40
41
42
43 @SuppressWarnings("FutureReturnValueIgnored" )
44 public class EchoServer {
45 private final AFSocketAddress addr;
46
47 public EchoServer(AFSocketAddress addr) {
48 this.addr = addr;
49 }
50
51 public void run() throws Exception {
52 SelectorProvider provider = AFUNIXSelectorProvider.provider();
53
54
55
56 EventLoopGroup bossGroup = new NioEventLoopGroup(0, (Executor) null, provider);
57 EventLoopGroup workerGroup = new NioEventLoopGroup(0, (Executor) null, provider);
58 try {
59 ServerBootstrap b = new ServerBootstrap();
60 b.group(bossGroup, workerGroup)
61 .channelFactory(() -> new NioServerSocketChannel(provider))
62 .childHandler(new ChannelInitializer<SocketChannel>() {
63 @Override
64 public void initChannel(SocketChannel ch) throws Exception {
65 ch.pipeline().addLast(new EchoServerHandler());
66 }
67 })
68 .option(ChannelOption.SO_BACKLOG, 128)
69 .childOption(ChannelOption.SO_KEEPALIVE, true);
70
71
72 ChannelFuture f = b.bind(addr).sync();
73
74
75
76
77 f.channel().closeFuture().sync();
78 } finally {
79 workerGroup.shutdownGracefully();
80 bossGroup.shutdownGracefully();
81 }
82 }
83
84 public static void main(String[] args) throws Exception {
85 File path = new File("/tmp/nettyecho");
86 if (args.length > 0) {
87 path = new File(args[0]);
88 }
89
90 AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(path);
91 System.out.println("Binding to " + addr);
92
93 new EchoServer(addr).run();
94
95 }
96 }