我已經開始使用netty,並且(顯然)想要在客戶端和服務器之間發送消息。由於我處於早期階段,所以我對簡單的東西有問題,在這種情況下,它會發送一條消息。這是我創造我的服務器和我的客戶:Netty - 頻道立即關閉
客戶:
public void run() throws Exception
{
EventLoopGroup group = new NioEventLoopGroup();
try
{
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new SecureChatClientInitializer());
b.option(ChannelOption.SO_KEEPALIVE, true);
// Start the connection attempt.
ChannelFuture future = b.connect(new InetSocketAddress(host, port));
Channel ch = future.awaitUninterruptibly().channel();
ch.writeAndFlush("hi\r\n");
// Wait until all messages are flushed before closing the channel.
if (lastWriteFuture != null)
{
lastWriteFuture.sync();
}
} finally
{
// The connection is closed automatically on shutdown.
group.shutdownGracefully();
}
}
服務器:
public void run() throws InterruptedException
{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try
{
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new SecureChatServerInitializer(sessionManager));
b.option(ChannelOption.SO_KEEPALIVE, true);
b.bind(port).sync().channel().closeFuture().sync();
} finally
{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
客戶初始化程序:
public class SecureChatClientInitializer extends ChannelInitializer<SocketChannel>
{
@Override
public void initChannel(SocketChannel ch) throws Exception
{
ChannelPipeline pipeline = ch.pipeline();
SSLEngine engine =
SecureChatSslContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new SecureChatClientHandler());
}
}
服務器初始化程序:
public class SecureChatServerInitializer extends ChannelInitializer<SocketChannel>
{
...
@Override
public void initChannel(SocketChannel ch) throws Exception
{
ChannelPipeline pipeline = ch.pipeline();
SSLEngine engine =
SecureChatSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new SecureChatServerHandler(sessionManager));
}
}
正如您可能已經從查看源代碼中猜到的一樣:是的,其中的一部分來自SecureChatExample。我編輯了部分內容,不明白爲什麼它不再工作。當執行客戶端,我只得到錯誤信息的一行:
java.nio.channels.ClosedChannelException
這做到了!謝謝! :d – user1406177