io.netty.channel.ChannelFuture Scala Examples

The following examples show how to use io.netty.channel.ChannelFuture. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: NettyFutureConverters.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal

import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import io.netty.util.concurrent.GenericFutureListener
import io.netty.util.concurrent.{ Future => NettyFuture }

import scala.concurrent.Future
import scala.concurrent.Promise

object NettyFutureConverters {
  implicit class ToFuture[T](future: NettyFuture[T]) {
    def toScala: Future[T] = {
      val promise = Promise[T]()
      future.addListener(new GenericFutureListener[NettyFuture[T]] {
        def operationComplete(future: NettyFuture[T]) = {
          if (future.isSuccess) {
            promise.success(future.getNow)
          } else if (future.isCancelled) {
            promise.failure(new RuntimeException("Future cancelled"))
          } else {
            promise.failure(future.cause())
          }
        }
      })
      promise.future
    }
  }

  implicit class ChannelFutureToFuture(future: ChannelFuture) {
    def channelFutureToScala: Future[Channel] = {
      val promise = Promise[Channel]()
      future.addListener(new ChannelFutureListener {
        def operationComplete(future: ChannelFuture) = {
          if (future.isSuccess) {
            promise.success(future.channel())
          } else if (future.isCancelled) {
            promise.failure(new RuntimeException("Future cancelled"))
          } else {
            promise.failure(future.cause())
          }
        }
      })
      promise.future
    }
  }
} 
Example 2
Source File: ChannelFutures.scala    From netty-in-action-scala   with Apache License 2.0 5 votes vote down vote up
package nia.chapter6

import io.netty.buffer.Unpooled
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import io.netty.channel.socket.nio.NioSocketChannel


  def addingChannelFutureListener(): Unit = {
    val channel = CHANNEL_FROM_SOMEWHERE
    // get reference to pipeline;
    val someMessage = SOME_MSG_FROM_SOMEWHERE
    //...
    val future = channel.write(someMessage)
    future.addListener(new ChannelFutureListener() {
      override def operationComplete(f: ChannelFuture): Unit = {
        if (!f.isSuccess) {
          f.cause.printStackTrace()
          f.channel.close
        }
      }
    })
  }
} 
Example 3
Source File: ChannelOperationExamples.scala    From netty-in-action-scala   with Apache License 2.0 5 votes vote down vote up
package nia.chapter4

import io.netty.buffer.Unpooled
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.util.CharsetUtil
import java.util.concurrent.Executors


  def writingToChannelFromManyThreads(): Unit = {
    val channel = CHANNEL_FROM_SOMEWHERE
    //创建持有要写数据的ByteBuf
    val buf = Unpooled.copiedBuffer("your data", CharsetUtil.UTF_8)
    //创建将数据写到Channel 的 Runnable
    val writer: Runnable = () ⇒ channel.write(buf.duplicate())
    //获取到线程池Executor 的引用
    val executor = Executors.newCachedThreadPool
    //递交写任务给线程池以便在某个线程中执行
    // write in one thread
    executor.execute(writer)
    //递交另一个写任务以便在另一个线程中执行
    // write in another thread
    executor.execute(writer)
    //...
  }
} 
Example 4
Source File: BootstrapSharingEventLoopGroup.scala    From netty-in-action-scala   with Apache License 2.0 5 votes vote down vote up
package nia.chapter8

import io.netty.bootstrap.Bootstrap
import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import java.net.InetSocketAddress


  def bootstrap(): Unit = { //创建 ServerBootstrap 以创建 ServerSocketChannel,并绑定它
    val bootstrap = new ServerBootstrap
    //设置 EventLoopGroup,其将提供用以处理 Channel 事件的 EventLoop
    bootstrap.group(new NioEventLoopGroup, new NioEventLoopGroup)
      //指定要使用的 Channel 实现
      .channel(classOf[NioServerSocketChannel])
      //设置用于处理已被接受的子 Channel 的 I/O 和数据的 ChannelInboundHandler
      .childHandler {
        new SimpleChannelInboundHandler[ByteBuf]() {
          private[chapter8] var connectFuture: ChannelFuture = _

          @throws[Exception]
          override def channelActive(ctx: ChannelHandlerContext): Unit = {
            //创建一个 Bootstrap 类的实例以连接到远程主机
            val bootstrap = new Bootstrap
            //指定 Channel 的实现
            bootstrap.channel(classOf[NioSocketChannel])
              .handler(new SimpleChannelInboundHandler[ByteBuf]() {
                @throws[Exception]
                override protected def channelRead0(
                  ctx: ChannelHandlerContext,
                  in:  ByteBuf): Unit = {
                  println("Received data")
                }
              })
            //使用与分配给已被接受的子Channel相同的EventLoop
            bootstrap.group(ctx.channel.eventLoop)
            //连接到远程节点
            connectFuture = bootstrap.connect(new InetSocketAddress("www.manning.com", 80))
          }

          @throws[Exception]
          override protected def channelRead0(
            channelHandlerContext: ChannelHandlerContext,
            byteBuf:               ByteBuf): Unit = {
            if (connectFuture.isDone) {
              //当连接完成时,执行一些数据操作(如代理)
              // do something with the data
            }
          }
        }
      }

    //通过配置好的 ServerBootstrap 绑定该 ServerSocketChannel
    val future = bootstrap.bind(new InetSocketAddress(8080))
    future.addListener(new ChannelFutureListener() {
      @throws[Exception]
      override def operationComplete(channelFuture: ChannelFuture): Unit = {
        if (channelFuture.isSuccess) System.out.println("Server bound")
        else {
          System.err.println("Bind attempt failed")
          channelFuture.cause.printStackTrace()
        }
      }
    })
  }
} 
Example 5
Source File: BootstrapServer.scala    From netty-in-action-scala   with Apache License 2.0 5 votes vote down vote up
package nia.chapter8

import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import java.net.InetSocketAddress


  def bootstrap(): Unit = {
    val group = new NioEventLoopGroup
    //创建 Server Bootstrap
    val bootstrap = new ServerBootstrap
    //设置 EventLoopGroup,其提供了用于处理 Channel 事件的EventLoop
    bootstrap.group(group)
      //指定要使用的 Channel 实现
      .channel(classOf[NioServerSocketChannel])
      //设置用于处理已被接受的子 Channel 的I/O及数据的 ChannelInboundHandler
      .childHandler {
        new SimpleChannelInboundHandler[ByteBuf]() {
          @throws[Exception]
          override protected def channelRead0(channelHandlerContext: ChannelHandlerContext, byteBuf: ByteBuf): Unit = {
            System.out.println("Received data")
          }
        }
      }

    //通过配置好的 ServerBootstrap 的实例绑定该 Channel
    val future = bootstrap.bind(new InetSocketAddress(8080))
    future.addListener(new ChannelFutureListener() {
      @throws[Exception]
      override def operationComplete(channelFuture: ChannelFuture): Unit = {
        if (channelFuture.isSuccess) System.out.println("Server bound")
        else {
          System.err.println("Bind attempt failed")
          channelFuture.cause.printStackTrace()
        }
      }
    })
  }
} 
Example 6
Source File: BootstrapDatagramChannel.scala    From netty-in-action-scala   with Apache License 2.0 5 votes vote down vote up
package nia.chapter8

import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.oio.OioEventLoopGroup
import io.netty.channel.socket.DatagramPacket
import io.netty.channel.socket.oio.OioDatagramChannel
import java.net.InetSocketAddress


  def bootstrap(): Unit = {
    //创建一个 Bootstrap 的实例以创建和绑定新的数据报 Channel
    val bootstrap = new Bootstrap
    //设置 EventLoopGroup,其提供了用以处理 Channel 事件的 EventLoop
    bootstrap.group(new OioEventLoopGroup)
      //指定 Channel 的实现
      .channel(classOf[OioDatagramChannel])
      .handler(new SimpleChannelInboundHandler[DatagramPacket]() {
        @throws[Exception]
        override def channelRead0(ctx: ChannelHandlerContext, msg: DatagramPacket): Unit = {
          // Do something with the packet
        }
      })

    //调用 bind() 方法,因为该协议是无连接的
    val future = bootstrap.bind(new InetSocketAddress(0))
    future.addListener(new ChannelFutureListener() {
      @throws[Exception]
      override def operationComplete(channelFuture: ChannelFuture): Unit = {
        if (channelFuture.isSuccess)
          println("Channel bound")
        else {
          System.err.println("Bind attempt failed")
          channelFuture.cause.printStackTrace()
        }
      }
    })
  }
} 
Example 7
Source File: GrpcGatewayServer.scala    From grpcgateway   with MIT License 5 votes vote down vote up
package grpcgateway.server

import grpcgateway.handlers.GrpcGatewayHandler
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.{ChannelFuture, EventLoopGroup}

class GrpcGatewayServer private[server] (
  port: Int,
  bootstrap: ServerBootstrap,
  masterGroup: EventLoopGroup,
  slaveGroup: EventLoopGroup,
  services: List[GrpcGatewayHandler]
) {
    private var channel: Option[ChannelFuture] = None

    def start(): Unit = {
      channel = Option(bootstrap.bind(port).sync())
    }

    def shutdown(): Unit = {
      slaveGroup.shutdownGracefully()
      masterGroup.shutdownGracefully()
      services.foreach(_.shutdown())
      channel.foreach(_.channel().closeFuture().sync())
    }
} 
Example 8
Source File: InboundConnectionFilter.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.network

import java.net.{InetAddress, InetSocketAddress}
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger

import com.wavesplatform.utils.ScorexLogging
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelFuture, ChannelHandlerContext}
import io.netty.handler.ipfilter.AbstractRemoteAddressFilter

@Sharable
class InboundConnectionFilter(peerDatabase: PeerDatabase, maxInboundConnections: Int, maxConnectionsPerHost: Int)
    extends AbstractRemoteAddressFilter[InetSocketAddress]
    with ScorexLogging {
  private val inboundConnectionCount = new AtomicInteger(0)
  private val perHostConnectionCount = new ConcurrentHashMap[InetAddress, Int]
  private val emptyChannelFuture     = null.asInstanceOf[ChannelFuture]

  private def dec(remoteAddress: InetAddress) = {
    inboundConnectionCount.decrementAndGet()
    log.trace(s"Number of inbound connections: ${inboundConnectionCount.get()}")
    perHostConnectionCount.compute(remoteAddress, (_, cnt) => cnt - 1)
    emptyChannelFuture
  }

  override def accept(ctx: ChannelHandlerContext, remoteAddress: InetSocketAddress): Boolean = Option(remoteAddress.getAddress) match {
    case None =>
      log.debug(s"Can't obtain an address from $remoteAddress")
      false

    case Some(address) =>
      val newTotal        = inboundConnectionCount.incrementAndGet()
      val newCountPerHost = perHostConnectionCount.compute(address, (_, cnt) => Option(cnt).fold(1)(_ + 1))
      val isBlacklisted   = peerDatabase.blacklistedHosts.contains(address)

      val accepted = newTotal <= maxInboundConnections &&
        newCountPerHost <= maxConnectionsPerHost &&
        !isBlacklisted

      log.trace(
        s"Check inbound connection from $remoteAddress: new inbound total = $newTotal, " +
          s"connections with this host = $newCountPerHost, address ${if (isBlacklisted) "IS" else "is not"} blacklisted, " +
          s"${if (accepted) "is" else "is not"} accepted"
      )

      accepted
  }

  override def channelAccepted(ctx: ChannelHandlerContext, remoteAddress: InetSocketAddress): Unit =
    ctx.channel().closeFuture().addListener((_: ChannelFuture) => Option(remoteAddress.getAddress).foreach(dec))

  override def channelRejected(ctx: ChannelHandlerContext, remoteAddress: InetSocketAddress): ChannelFuture =
    Option(remoteAddress.getAddress).fold(emptyChannelFuture)(dec)
} 
Example 9
Source File: TransportServer.scala    From aloha   with Apache License 2.0 5 votes vote down vote up
package me.jrwang.aloha.transport.server

import java.io.Closeable
import java.net.InetSocketAddress
import java.util.concurrent.TimeUnit

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.{ChannelFuture, ChannelInitializer, ChannelOption}
import io.netty.channel.socket.SocketChannel
import me.jrwang.aloha.common.Logging
import me.jrwang.aloha.common.util.Utils
import me.jrwang.aloha.transport.TransportContext
import me.jrwang.aloha.transport.util.{IOMode, NettyUtils}


class TransportServer(
    transportContext: TransportContext,
    hostToBind: String,
    portToBind: Int,
    appRpcHandler: RpcHandler,
    bootstraps: List[TransportServerBootstrap]
  ) extends Closeable with Logging {
  private val conf  = transportContext.conf

  private var port: Int = -1
  private var bootstrap: ServerBootstrap = _
  private var channelFuture: ChannelFuture = _

  try
    init()
  catch {
    case e: RuntimeException =>
      Utils.closeQuietly(this)
      throw e
  }

  def init(): Unit = {
    val ioMode = IOMode.valueOf(conf.ioMode)
    val bossGroup = NettyUtils.createEventLoop(ioMode, conf.serverThreads, conf.module + "-server")
    val workerGroup = bossGroup
    val allocator = NettyUtils.createPooledByteBufAllocator(conf.preferDirectBufs, true , conf.serverThreads)

    bootstrap = new ServerBootstrap()
      .group(bossGroup, workerGroup)
      .channel(NettyUtils.getServerChannelClass(ioMode))
      .option(ChannelOption.ALLOCATOR, allocator)
      .childOption(ChannelOption.ALLOCATOR, allocator)

    if (conf.backLog > 0)
      bootstrap.option[java.lang.Integer](ChannelOption.SO_BACKLOG, conf.backLog)
    if (conf.receiveBuf > 0)
      bootstrap.childOption[java.lang.Integer](ChannelOption.SO_RCVBUF, conf.receiveBuf)
    if (conf.sendBuf > 0)
      bootstrap.childOption[java.lang.Integer](ChannelOption.SO_SNDBUF, conf.sendBuf)

    bootstrap.childHandler(new ChannelInitializer[SocketChannel]() {
      override protected def initChannel(ch: SocketChannel): Unit = {
        val rpcHandler = bootstraps.foldLeft[RpcHandler](appRpcHandler)((r, b) => {
          b.doBootstrap(ch, r)
        })
        transportContext.initializePipeline(ch, rpcHandler)
      }
    })

    val address = if (hostToBind == null)
      new InetSocketAddress(portToBind)
    else
      new InetSocketAddress(hostToBind, portToBind)
    channelFuture = bootstrap.bind(address)
    channelFuture.syncUninterruptibly
    port = channelFuture.channel.localAddress.asInstanceOf[InetSocketAddress].getPort
    logDebug(s"Transport server started on port: $port")
  }

  def getPort: Int = {
    if (port == -1)
      throw new IllegalStateException("Server not initialized")
    port
  }

  def awaitTermination(): Unit = {
    channelFuture.channel().closeFuture().sync()
  }

  override def close(): Unit = {
    if (channelFuture != null) {
      // close is a local operation and should finish within milliseconds; timeout just to be safe
      channelFuture.channel.close.awaitUninterruptibly(10, TimeUnit.SECONDS)
      channelFuture = null
    }
    if (bootstrap != null && bootstrap.config().group() != null)
      bootstrap.config().group().shutdownGracefully
    if (bootstrap != null && bootstrap.config().childGroup() != null)
      bootstrap.config().childGroup().shutdownGracefully
    bootstrap = null
  }
} 
Example 10
Source File: package.scala    From asyncdb   with Apache License 2.0 5 votes vote down vote up
package io.asyncdb

import cats.effect._
import io.netty.channel.{ChannelFuture, ChannelFutureListener}

package object netty {
  implicit class ChannelFutureOps(val future: ChannelFuture) extends AnyVal {
    def to[F[_]](implicit F: Concurrent[F]): F[ChannelFuture] = F.cancelable {
      k =>
        val f = future.addListener(new ChannelFutureListener {
          override def operationComplete(future: ChannelFuture): Unit = {
            if (future.isSuccess) k(Right(future)) else k(Left(future.cause()))
          }
        })
        F.delay(f.cancel(false))
    }
  }
}