我正在尝试创建一个使用 Netty 的 SnappyFrameEncoder/Decoder 的简单程序。我创建了一个使用 LocalChannels 作为服务器/客户端的小型 Java 应用程序。
客户端使用 Snappy 对字符串进行编码,服务器对字符串进行解码并将其写入控制台。
我不断收到 StackOverFlow 异常,即使我将其拆分为单独的客户端/服务器程序。
如果我从管道中注释掉 SnappyFramedDecoder 和 SnappyFramedEncoder,它会正常运行并输出我的测试消息。
我尝试了很长的测试消息,但它仍然给了我一个 StackOverFlow 异常。
谁能帮帮我?我是 Netty 的新手。谢谢!!
我正在使用 Netty 4.0.0.CR2
这是我的代码:
public class LocalNettyTest {
private static String LOCAL_ID = "localtest";
private static String TEST_STRING = "TEST";
public void run() throws Exception {
final LocalAddress addr = new LocalAddress(LOCAL_ID);
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
EventLoopGroup serverGroup = new LocalEventLoopGroup();
EventLoopGroup clientGroup = new LocalEventLoopGroup();
try {
sb.group(serverGroup)
.channel(LocalServerChannel.class)
.handler(new ChannelInitializer<LocalServerChannel>(){
@Override
public void initChannel(LocalServerChannel ch) throws Exception {
ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
}
})
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new SnappyFramedDecoder());
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new ChannelInboundMessageHandlerAdapter<String>() {
@Override
public void messageReceived(ChannelHandlerContext ctx,
String msg) throws Exception {
System.out.println ("RECEIVED: " + msg);
}
});
}
});
cb.group(clientGroup)
.channel(LocalChannel.class)
.handler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder ());
ch.pipeline().addLast(new SnappyFramedEncoder ());
}
});
// Start the server.
sb.bind(addr).sync();
// Start the client.
Channel ch = cb.connect(addr).sync().channel();
ChannelFuture lastWriteFuture = ch.write(TEST_STRING);
// Wait until all messages are flushed before closing the channel.
if (lastWriteFuture != null) {
System.out.println ("Waiting");
lastWriteFuture.awaitUninterruptibly();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
serverGroup.shutdownGracefully();
clientGroup.shutdownGracefully();
}
System.out.println ("Done");
}
public static void main(String[] args) throws Exception {
new LocalNettyTest().run();
}
}