【问题标题】:How could a Netty server send data to different clients?Netty 服务器如何将数据发送到不同的客户端?
【发布时间】:2014-10-31 12:36:16
【问题描述】:

我想做一些简单的聊天。 服务器必须在客户端列表中添加新客户端,并且当一个客户端向服务器发送消息时,服务器必须将此消息重新发送给其他客户端。 我知道如何从客户端读取消息,但我不知道如何将消息从服​​务器发送到客户端。而且我不确定客户列表应该在哪里,但猜测在处理程序类中。 这是我初始化服务器类的主类

package firstPackage;

public class main {

    public static void main(String[] args) throws Exception
    {
    Server server = new Server(9050);
    server.run();
    }
}

这里是服务器类

package firstPackage;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import io.netty.channel.socket.SocketChannel;


public class Server {

private int port;

public Server(int port)
{
    this.port=port;
}

public void run() throws Exception
{
    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(new DiscardServerHandler());
             }
         })
         .option(ChannelOption.SO_BACKLOG,128)
         .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    }
    finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

}

这里是 Handler 类

package firstPackage;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    try {
        while (in.isReadable()) {
            System.out.print((char) in.readByte());
            System.out.flush();
        }
        System.out.println();

        ctx.writeAndFlush("hey"); // вот здесь я думал, что сообщение будет отправлятся клиенту, от которого я получил сообщение, но не отправляется

    } finally {
        ReferenceCountUtil.release(msg);
    }
}

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channel is active");
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channel is invactive");
}

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    System.out.println("handler added");
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
}
}

其实我现在没有客户端列表,因为我什至不知道这个列表必须包含什么类型的对象,在C#中是Socket对象,那么在Netty中呢?

【问题讨论】:

    标签: java netty


    【解决方案1】:

    我打赌this example 应该会帮助你(这是一个 YouTube 视频,所以请不要让 cmets 知道链接损坏)。特别是,它使用ChannelGroup 来解决您提出的问题。而且,是的,它进入服务器端的处理程序中。

    编辑:

    还要注意,在示例中,ChannelGroup 是静态的。我可能会争辩说最好不要使用静态成员并将ChannelGroup 从服务器类注入到处理程序中,但是如果您只想让某些东西快速工作,那么静态成员的简单性可能会更可取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多