在Netty

时间:2016-01-10 13:02:21

标签: java netty

我正在使用Netty 5.0。

我有一个补充的客户端引导程序,我从netty github获取了SecureChatClient.java示例。 Wenn我从客户端bootstrap发送消息到服务器它完全正常。当我尝试从服务器引导程序向客户端发送消息时(首先通过客户端成功启动连接/通道后),我得到一个java.lang.UnsupportedOperationException,但没有任何进一步的信息。从服务器向客户端发送消息是通过上面的代码完成的。

是仅用于接收的serverbootstrap吗?

如上所示,serverbootstrap不能将消息写回客户端吗?我的意思是,消息可以通过ChannelHandler从套接字进入ChannelPipeline,但只有ChannelHandler应该将响应写回ChannelPipeline并退出套接字。因此,在ServerBootstrap中,用户并不意味着能够从Pipeline外部沿ChannelPipeline发送消息。 (希望有意义)

或者我只是遗漏了什么?

我的代码如下:

    // Ports.
    int serverPort = 8080;

    EventLoopGroup bossGroup    = new NioEventLoopGroup();
    EventLoopGroup workerGroup  = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ch.pipeline().addLast("MyMessageHandler", new MyMessageHandler());
             }
         })
         .option(ChannelOption.SO_BACKLOG, 128)
         .childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(serverPort).sync();
        Channel ch = f.channel();

        System.out.println("Server: Running!");

      // Read commands from the stdin.
      ChannelFuture lastWriteFuture = null;
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      while(true)
      {
          String line = in.readLine();
          if (line == null) break;

          ByteBuf getOut = buffer(64);
          getOut.writeBytes(line.getBytes());

          // Sends the received line to the server.
          lastWriteFuture = ch.writeAndFlush(getOut);

          lastWriteFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture cf) throws Exception {
                    if(cf.isSuccess()) {
                        System.out.println("CFListener: SUCCESS! YEAH! HELL! YEAH!");
                    } else {
                        System.out.println("CFListener: failure! FAILure! FAILURE!");
                        System.out.println(cf.cause());
                    }
                }
            });

      }

               // Wait until all messages are flushed before closing the channel.
      if (lastWriteFuture != null) {
          lastWriteFuture.sync();
      }


        // 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();
    } catch (InterruptedException | UnsupportedOperationException e) {
        e.printStackTrace();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

我开始使用以下示例:https://github.com/netty/netty/tree/4.1/example/src/main/java/io/netty/example/securechat

我的问题是,在调用ch.writeAndFlush时出现以下异常:

java.lang.UnsupportedOperationException
at io.netty.channel.socket.nio.NioServerSocketChannel.filterOutboundMessage(NioServerSocketChannel.java:184)
at io.netty.channel.AbstractChannel$AbstractUnsafe.write(AbstractChannel.java:784)
at io.netty.channel.DefaultChannelPipeline$HeadContext.write(DefaultChannelPipeline.java:1278)
at io.netty.channel.ChannelHandlerInvokerUtil.invokeWriteNow(ChannelHandlerInvokerUtil.java:158)
at io.netty.channel.DefaultChannelHandlerInvoker$WriteTask.run(DefaultChannelHandlerInvoker.java:440)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:328)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)

2 个答案:

答案 0 :(得分:3)

您无法写入ServerChannel,只能连接到普通频道。由于这个原因,您对writeAndFlush的调用失败了。

要向每个客户端发送消息,您应该将每个客户端的通道存储在ChannelGroup内,并在其上调用writeAndFlush()。

快速执行此操作的方法是向ServerBootstrap添加另一个处理程序,将传入连接放入ChannelGroup中,快速实现此操作:

// In your main:
ChannelGroup allChannels =
         new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

// In your ChannelInitializer<SocketChannel>
ch.pipeline().addLast("grouper", new GlobalSendHandler());

// New class:
public class MyHandler extends ChannelInboundHandlerAdapter {
     @Override
     public void channelActive(ChannelHandlerContext ctx) {
         allChannels.add(ctx.channel());
         super.channelActive(ctx);
     }
 }

然后我们可以调用以下内容向每个连接发送消息,这会返回ChannelGroupFuture而不是正常的ChannelFuture

allChannels.writeAndFlush(getOut);

您的总代码看起来像上面的修补程序:

// Ports.
int serverPort = 8080;

ChannelGroup allChannels =
         new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

EventLoopGroup bossGroup    = new NioEventLoopGroup();
EventLoopGroup workerGroup  = new NioEventLoopGroup();
try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
     .channel(NioServerSocketChannel.class)
     .childHandler(new ChannelInitializer<SocketChannel>() {
         @Override
         public void initChannel(SocketChannel ch) throws Exception {
             ch.pipeline().addLast("MyMessageHandler", new MyMessageHandler());
             ch.pipeline().addLast("grouper", new GlobalSendHandler());
         }
     })
     .option(ChannelOption.SO_BACKLOG, 128)
     .childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(serverPort).sync();
    Channel ch = f.channel();

    System.out.println("Server: Running!");

  // Read commands from the stdin.
  ChannelGroupFuture lastWriteFuture = null;
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  while(true)
  {
      String line = in.readLine();
      if (line == null) break;

      ByteBuf getOut = buffer(64);
      getOut.writeBytes(line.getBytes());

      // Sends the received line to the server.
      lastWriteFuture = allChannels.writeAndFlush(getOut);

      lastWriteFuture.addListener(new ChannelGroupFutureListener() {
            @Override
            public void operationComplete(ChannelGroupFuture cf) throws Exception {
                if(cf.isSuccess()) {
                    System.out.println("CFListener: SUCCESS! YEAH! HELL! YEAH!");
                } else {
                    System.out.println("CFListener: failure! FAILure! FAILURE!");
                    System.out.println(cf.cause());
                }
            }
        });

  }

           // Wait until all messages are flushed before closing the channel.
  if (lastWriteFuture != null) {
      lastWriteFuture.sync();
  }


    // 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();
} catch (InterruptedException | UnsupportedOperationException e) {
    e.printStackTrace();
} finally {
    workerGroup.shutdownGracefully();
    bossGroup.shutdownGracefully();
}

答案 1 :(得分:1)

我认为Netty Server没有解码器,编码器。 如果你想发送字符串数据,

Appdata

添加服务器的初始化程序!