在netty上,如何在客户机(boostrap)连接上使用服务器bootstrap的相同ip/端口?

bksxznpy  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(447)

我有一个voip服务器,可以监听tcp端口5000。此端口对于所有接收和建立的连接都是必需的。既然服务器引导使用的是端口5000,如何创建源端口为5000的客户端tcp连接?
示例场景:客户a呼叫客户b。需要分别拨打两个电话:
a(端口5111)->服务器(端口5000)
服务器(端口5000)->b(端口9999)
呼叫1时,目标端口=5000(服务器引导)。on call 2源端口需要为5000(客户端引导)。
有人能给我点灯吗?
服务器

EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap tcpBootstrap = new ServerBootstrap();
        tcpBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>()
        {
            @Override
            public void initChannel(final SocketChannel ch) throws Exception
            {
                final ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new SipMessageStreamDecoder());
                pipeline.addLast("encoder", new SipMessageEncoder());
                pipeline.addLast("handler", new DialerHandlerTCP());
            }
        })
        .option(ChannelOption.SO_BACKLOG, 128)
        .option(ChannelOption.SO_REUSEADDR, true)
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
        .childOption(ChannelOption.SO_KEEPALIVE, true)
        .childOption(ChannelOption.TCP_NODELAY, true);

        tcpBootstrap.bind(socketAddress).sync().channel();

客户机代码

Bootstrap bootstrapClient = new Bootstrap();

        bootstrapClient.group(networkBind.channel.eventLoop()).channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>()
        {
            @Override
            public void initChannel(final SocketChannel ch) throws Exception
            {
                final ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new SipMessageStreamDecoder());
                pipeline.addLast("encoder", new SipMessageEncoder());
                pipeline.addLast("handler", new DialerHandlerTCP());
            }
        });
djmepvbi

djmepvbi1#

您可以使用以下引导类方法添加套接字地址:

public Bootstrap remoteAddress(SocketAddress remoteAddress)
public Bootstrap remoteAddress(String inetHost, int inetPort)
public Bootstrap remoteAddress(InetAddress inetHost,int inetPort)

在您的示例中,可以如下所示:

bootstrapClient.group(networkBind.channel.eventLoop())
               .channel(NioSocketChannel.class)
               .remoteAddress(new InetSocketAddress(host, port))
               .handler(new ChannelInitializer<SocketChannel>()
        {
            @Override
            public void initChannel(final SocketChannel ch) throws Exception
            {
                final ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new SipMessageStreamDecoder());
                pipeline.addLast("encoder", new SipMessageEncoder());
                pipeline.addLast("handler", new DialerHandlerTCP());
            }
        });

相关问题