EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new 6MessageDecoder(),
new LoginHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128
) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
我在clojure中写道:
(let [bossGroup (NioEventLoopGroup.)
workerGroup (NioEventLoopGroup.)
bootstrap (ServerBootstrap.)]
(.. bootstrap
(group bossGroup workerGroup)
(channel NioServerSocketChannel)
(childHandler
(proxy [ChannelInitializer] []
(initChannel [ch]
(.. ch
(pipeline)
(addLast
(MessageDecoder.)
(LoginHandler.)
))
)))
(option ChannelOption/SO_BACKLOG, (int 128))
(childOption ChannelOption/SO_KEEPALIVE, true)
(bind (int 8080))
(sync)
(channel)
(closeFuture)
(sync)
;(childHandler (ChannelInitializer<SocketChannel>.))
)
)
用clojure编写的代码可以运行,但是当我测试它时:
telnet 127.0.0.1 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
它不起作用。但是,Java代码可以工作。它有什么问题?
答案 0 :(得分:0)
有原因: 在clojure中,java的变量参数不受支持。(从我的观点来看。) 所以, (addlast仅 (MessageDecoder。) (LoginHandler。) ) 调用
的语法不正确addLast(ChannelHandler... handlers) `
netty投诉&#34;找不到方法&#34;但它捕获异常并使用log4j打印警告。由于未配置log4j,我之前没有看到此警告。
输出:
Escape character is '^]'.
表示绑定和听力有效。
现在它使用了这段代码:
(.addLast
(.pipeline ch)
(doto (make-array ChannelHandler 2)
(aset 0 (MessageDecoder.))
(aset 2 (ServerHandler.))
)
)