java - netty4 :How to listen on multiple ports on a java process

标签 java port netty

我正在尝试监听两个不同端口上的连接

我在java main方法中启动2个线程,每个线程都与netty4绑定(bind)一个端口,但不能 听众成功! 这是我的代码,端口3333可以,但是1234不行,看起来3333被阻塞了!

    public class ObjectServer
    {
private static final Logger logger = LoggerFactory.getLogger(ObjectServer.class);

private String ip;
private int port;

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

public void run(final ChannelInboundHandlerAdapter handler) throws Exception
{
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try
    {
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>()
        {
            @Override
            public void initChannel(SocketChannel ch) throws Exception
            {
                ch.pipeline().addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), handler);
            }
        });
        server.bind(port).sync().channel().closeFuture().sync();
    }
    catch (Exception e)
    {
        logger.error("开启监听失败!端口[" + port + "]", e);
        throw e;
    }
    finally
    {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

}

 public class SocketServer
{
private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);
private static final StringDecoder DECODER = new StringDecoder();
private static final StringEncoder ENCODER = new StringEncoder();
private int port;

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

public void run(final ChannelInboundHandlerAdapter handler) 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
            {
                ChannelPipeline pipeline = ch.pipeline();
                // Add the text line codec combination first,
                pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                // the encoder and decoder are static as these are
                // sharable
                pipeline.addLast("encoder", ENCODER);
                pipeline.addLast("decoder", DECODER);
                // and then business logic.
                pipeline.addLast("handler", handler);
            }
        });
        b.bind(port).sync().channel().closeFuture().sync();
    }
    catch (Exception e)
    {
        logger.error("开启监听失败!端口[" + port + "]", e);
        throw e;
    }
    finally
    {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

}

 public class Test
       {
    public static void main(String[] args) throws Exception
    {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread2.start();
        thread1.start();
        new SocketClient("192.168.16.52", 3333).run(new TestHandler4("test4"));
        new ObjectClient("192.168.16.52", 1234).run(new TestHandler3("test3"));
    }

    @Sharable
    static class TestHandler1 extends ChannelInboundHandlerAdapter
    {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
        {
            System.out.println("1234" + msg);
        }

    }

    static class Thread1 extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                new ObjectServer(1234).run(new TestHandler1());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    static class Thread2 extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                new SocketServer(3333).run(new TestHandler2());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    @Sharable
    static class TestHandler2 extends SimpleChannelInboundHandler<String>
    {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception
        {
            System.out.println("3333" + msg);
        }

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

    @Sharable
    static class TestHandler3 extends ChannelInboundHandlerAdapter
    {
        private String msg;

        public TestHandler3(String msg)
        {
            this.msg = msg;
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception
        {
            ctx.writeAndFlush(msg);
        }
    }

    @Sharable
    static class TestHandler4 extends SimpleChannelInboundHandler<String>
    {
        private String msg;

        public TestHandler4(String msg)
        {
            this.msg = msg;
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception
        {
            ctx.writeAndFlush(msg);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext arg0, String arg1)throws     Exception 
        {

        }
    }
}

最佳答案

在您的 run() 实现中,您执行以下操作:

server.bind(port).sync().channel().closeFuture().sync();

.. 它将阻塞,直到服务器套接字关闭。因为您没有关闭服务器套接字,所以它永远不会返回。因此,只有第一个服务器套接字将被绑定(bind)。

您可能想要的只是绑定(bind)并返回,而不是等待服务器套接字关闭。

关于java - netty4 :How to listen on multiple ports on a java process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21986471/

相关文章:

android - 试图通过我的 android 客户端访问我的 openfire 服务器

java - 在链表中搜索现有成员时返回 boolean 结果 - java

java - 是否始终调用 gc,即使堆空间在运行时连续可用?

cassandra - 关闭 Cassandra 服务器,然后在 Windows 7 中重新启动它

php - Apache 意外关闭

java - 如何使用Netty从设备读取完整数据?

netty - 在 ThreadPoolExecutors 中优先处理 Netty 任务

java - 当 ChannelOutboundBuffer 已满时写入会发生什么

java - 树莓派四轴飞行器高速运转

java - 当我装饰对象时变量重置为默认值