io.netty.channel.EventLoopGroup Scala Examples

The following examples show how to use io.netty.channel.EventLoopGroup. 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: EventLoopGroupOwner.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.apiserver

import java.util.UUID
import java.util.concurrent.TimeUnit.MILLISECONDS

import com.daml.resources.{Resource, ResourceOwner}
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.{NioServerSocketChannel, NioSocketChannel}
import io.netty.channel.{Channel, EventLoopGroup, ServerChannel}
import io.netty.util.concurrent.DefaultThreadFactory

import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Try

final class EventLoopGroupOwner(threadPoolName: String, parallelism: Int)
    extends ResourceOwner[EventLoopGroup] {

  override def acquire()(implicit executionContext: ExecutionContext): Resource[EventLoopGroup] =
    Resource(
      Future(new NioEventLoopGroup(
        parallelism,
        new DefaultThreadFactory(s"$threadPoolName-grpc-event-loop-${UUID.randomUUID()}", true))))(
      group => {
        val promise = Promise[Unit]()
        val future = group.shutdownGracefully(0, 0, MILLISECONDS)
        future.addListener((f: io.netty.util.concurrent.Future[_]) =>
          promise.complete(Try(f.get).map(_ => ())))
        promise.future
      }
    )
}

object EventLoopGroupOwner {

  val clientChannelType: Class[_ <: Channel] = classOf[NioSocketChannel]

  val serverChannelType: Class[_ <: ServerChannel] = classOf[NioServerSocketChannel]

} 
Example 2
Source File: ServerEventLoopGroups.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.apiserver

import com.daml.resources.{Resource, ResourceOwner}
import io.grpc.netty.NettyServerBuilder
import io.netty.channel.{EventLoopGroup, ServerChannel}

import scala.concurrent.ExecutionContext

case class ServerEventLoopGroups(
    worker: EventLoopGroup,
    boss: EventLoopGroup,
    channelType: Class[_ <: ServerChannel],
) {

  def populate(builder: NettyServerBuilder): NettyServerBuilder =
    builder
      .channelType(channelType)
      .bossEventLoopGroup(boss)
      .workerEventLoopGroup(worker)

}

object ServerEventLoopGroups {

  final class Owner(name: String, workerParallelism: Int, bossParallelism: Int)
      extends ResourceOwner[ServerEventLoopGroups] {
    override def acquire()(
        implicit executionContext: ExecutionContext
    ): Resource[ServerEventLoopGroups] =
      Resource
        .sequence(
          Seq(
            new EventLoopGroupOwner(s"$name-worker", parallelism = workerParallelism).acquire(),
            new EventLoopGroupOwner(s"$name-boss", parallelism = bossParallelism).acquire(),
          ))
        .map {
          case Seq(worker, boss) =>
            ServerEventLoopGroups(
              worker = worker,
              boss = boss,
              channelType = EventLoopGroupOwner.serverChannelType,
            )
        }
  }

} 
Example 3
Source File: GrpcClientResource.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.sandbox.services

import java.net.{InetAddress, InetSocketAddress}
import java.util.concurrent.TimeUnit

import com.daml.platform.apiserver.EventLoopGroupOwner
import com.daml.ports.Port
import com.daml.resources.{Resource, ResourceOwner}
import io.grpc.Channel
import io.grpc.netty.NettyChannelBuilder
import io.netty.channel.EventLoopGroup

import scala.concurrent.{ExecutionContext, Future}

object GrpcClientResource {
  def owner(port: Port): ResourceOwner[Channel] =
    for {
      eventLoopGroup <- new EventLoopGroupOwner("api-client", sys.runtime.availableProcessors())
      channel <- channelOwner(port, EventLoopGroupOwner.clientChannelType, eventLoopGroup)
    } yield channel

  private def channelOwner(
      port: Port,
      channelType: Class[_ <: io.netty.channel.Channel],
      eventLoopGroup: EventLoopGroup,
  ): ResourceOwner[Channel] =
    new ResourceOwner[Channel] {
      override def acquire()(implicit executionContext: ExecutionContext): Resource[Channel] = {
        Resource(Future {
          NettyChannelBuilder
            .forAddress(new InetSocketAddress(InetAddress.getLoopbackAddress, port.value))
            .channelType(channelType)
            .eventLoopGroup(eventLoopGroup)
            .usePlaintext()
            .directExecutor()
            .build()
        })(channel =>
          Future {
            channel.shutdownNow()
            if (!channel.awaitTermination(5, TimeUnit.SECONDS)) {
              sys.error(
                "Unable to shutdown channel to a remote API under tests. Unable to recover. Terminating.")
            }
        })
      }
    }
} 
Example 4
Source File: JavadslWebSocketClient.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.client

import javax.inject.Inject
import javax.inject.Singleton

import com.lightbend.lagom.internal.client.WebSocketClient
import com.lightbend.lagom.internal.client.WebSocketClientConfig
import com.typesafe.config.Config
import io.netty.channel.EventLoopGroup
import play.api.Environment
import play.api.inject.ApplicationLifecycle

import scala.concurrent.ExecutionContext

@Singleton
class JavadslWebSocketClient(
    environment: Environment,
    config: WebSocketClientConfig,
    eventLoop: EventLoopGroup,
    lifecycle: ApplicationLifecycle
)(implicit ec: ExecutionContext)
    extends WebSocketClient(environment, config, eventLoop, lifecycle)
    with JavadslServiceApiBridge {
  // Constructor that manages its own event loop
  @Inject
  def this(environment: Environment, config: Config, applicationLifecycle: ApplicationLifecycle)(
      implicit ec: ExecutionContext
  ) = {
    this(
      environment,
      WebSocketClientConfig(config),
      WebSocketClient.createEventLoopGroup(applicationLifecycle),
      applicationLifecycle
    )
  }
} 
Example 5
Source File: ScaladslWebSocketClient.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.scaladsl.client

import com.lightbend.lagom.internal.client.WebSocketClient
import com.lightbend.lagom.internal.client.WebSocketClientConfig
import com.typesafe.config.Config
import io.netty.channel.EventLoopGroup
import play.api.Environment
import play.api.inject.ApplicationLifecycle

import scala.concurrent.ExecutionContext

private[lagom] class ScaladslWebSocketClient(
    environment: Environment,
    config: WebSocketClientConfig,
    eventLoop: EventLoopGroup,
    lifecycle: ApplicationLifecycle
)(implicit ec: ExecutionContext)
    extends WebSocketClient(environment, config, eventLoop, lifecycle)
    with ScaladslServiceApiBridge {
  // Constructor that manages its own event loop
  def this(environment: Environment, config: WebSocketClientConfig, applicationLifecycle: ApplicationLifecycle)(
      implicit ec: ExecutionContext
  ) = {
    this(environment, config, WebSocketClient.createEventLoopGroup(applicationLifecycle), applicationLifecycle)
  }
} 
Example 6
Source File: Global.scala    From wowchat   with GNU General Public License v3.0 5 votes vote down vote up
package wowchat.common

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

import io.netty.channel.EventLoopGroup
import net.dv8tion.jda.core.entities.TextChannel
import wowchat.discord.Discord
import wowchat.game.GameCommandHandler

import scala.collection.mutable

object Global {

  var group: EventLoopGroup = _
  var config: WowChatConfig = _

  var discord: Discord = _
  var game: Option[GameCommandHandler] = None

  val discordToWow = new mutable.HashMap[String, mutable.Set[WowChannelConfig]]
    with mutable.MultiMap[String, WowChannelConfig]
  val wowToDiscord = new mutable.HashMap[(Byte, Option[String]), mutable.Set[(TextChannel, DiscordChannelConfig)]]
    with mutable.MultiMap[(Byte, Option[String]), (TextChannel, DiscordChannelConfig)]
  val guildEventsToDiscord = new mutable.HashMap[String, mutable.Set[TextChannel]]
    with mutable.MultiMap[String, TextChannel]

  def getTime: String = {
    LocalDateTime.now.format(DateTimeFormatter.ofPattern("HH:mm:ss"))
  }
} 
Example 7
Source File: LogEventBroadcaster.scala    From netty-in-action-scala   with Apache License 2.0 5 votes vote down vote up
package nia.chapter13

import io.netty.bootstrap.Bootstrap
import io.netty.channel.{ ChannelOption, EventLoopGroup }
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioDatagramChannel
import java.io.File
import java.io.RandomAccessFile
import java.net.InetSocketAddress
import java.lang.{ Boolean ⇒ JBoolean }
import java.util.Objects

import scala.util.control.Breaks._


object LogEventBroadcaster {

  @throws[Exception]
  def main(args: Array[String]): Unit = {
    if (args.length != 2)
      throw new IllegalArgumentException

    //创建并启动一个新的 LogEventBroadcaster 的实例
    val broadcaster =
      new LogEventBroadcaster(new InetSocketAddress("255.255.255.255", args(0).toInt), new File(args(1)))

    try {
      broadcaster.run()
    } finally {
      broadcaster.stop()
    }
  }
}

class LogEventBroadcaster(address: InetSocketAddress, file: File) {
  val group: EventLoopGroup = new NioEventLoopGroup
  val bootstrap = new Bootstrap

  //引导该 NioDatagramChannel(无连接的)
  bootstrap
    .group(group)
    .channel(classOf[NioDatagramChannel])
    //设置 SO_BROADCAST 套接字选项
    .option[JBoolean](ChannelOption.SO_BROADCAST, true)
    .handler(new LogEventEncoder(address))

  @throws[Exception]
  def run(): Unit = { //绑定 Channel
    val ch = bootstrap.bind(0).sync.channel
    var pointer: Long = 0
    //启动主处理循环

    breakable {
      while (true) {
        val len = file.length
        if (len < pointer) { // file was reset
          //如果有必要,将文件指针设置到该文件的最后一个字节
          pointer = len
        } else if (len > pointer) { // Content was added
          val raf = new RandomAccessFile(file, "r")
          //设置当前的文件指针,以确保没有任何的旧日志被发送
          raf.seek(pointer)
          Iterator.continually(raf.readLine())
            .takeWhile(Objects.nonNull)
            .foreach { line ⇒
              ch.writeAndFlush(LogEvent(file.getAbsolutePath, line))
            }
          //存储其在文件中的当前位置
          pointer = raf.getFilePointer
          raf.close()
        }
        try {
          //休眠 1 秒,如果被中断,则退出循环;否则重新处理它
          Thread.sleep(1000)
        } catch {
          case e: InterruptedException ⇒
            Thread.interrupted
            break
        }
      }
    }
  }

  def stop(): Unit = {
    group.shutdownGracefully()
  }
} 
Example 8
Source File: EchoClient.scala    From netty-in-action-scala   with Apache License 2.0 5 votes vote down vote up
package nia.chapter2.echoclient

import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelInitializer
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import java.net.InetSocketAddress


object EchoClient {
  @throws[Exception]
  def main(args: Array[String]): Unit = {
    if (args.length != 2) {
      System.err.println("Usage: " + classOf[EchoClient].getSimpleName + " <host> <port>")
    } else {
      val host = args(0)
      val port = args(1).toInt
      new EchoClient(host, port).start()
    }
  }
}

class EchoClient(val host: String, val port: Int) {
  @throws[Exception]
  def start(): Unit = {
    val group: EventLoopGroup = new NioEventLoopGroup
    try {
      //创建 Bootstrap
      val b = new Bootstrap
      //指定 EventLoopGroup 以处理客户端事件;需要适用于 NIO 的实现
      b.group(group)
        //适用于 NIO 传输的Channel 类型
        .channel(classOf[NioSocketChannel])
        //设置服务器的InetSocketAddress
        .remoteAddress(new InetSocketAddress(host, port))
        //在创建Channel时,向 ChannelPipeline中添加一个 EchoClientHandler实例
        .handler {
          new ChannelInitializer[SocketChannel]() {
            @throws[Exception]
            override def initChannel(ch: SocketChannel): Unit = {
              ch.pipeline.addLast(new EchoClientHandler)
            }
          }
        }
      //连接到远程节点,阻塞等待直到连接完成
      val f = b.connect.sync()
      //阻塞,直到Channel 关闭
      f.channel.closeFuture.sync()
    } finally {
      //关闭线程池并且释放所有的资源
      group.shutdownGracefully.sync()
    }
  }
} 
Example 9
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 10
Source File: NettyUtils.scala    From aloha   with Apache License 2.0 5 votes vote down vote up
package me.jrwang.aloha.transport.util

import io.netty.buffer.PooledByteBufAllocator
import io.netty.channel.{Channel, EventLoopGroup, ServerChannel}
import io.netty.channel.epoll.{EpollEventLoopGroup, EpollServerSocketChannel, EpollSocketChannel}
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.{NioServerSocketChannel, NioSocketChannel}
import io.netty.util.concurrent.DefaultThreadFactory
import io.netty.util.internal.PlatformDependent
import me.jrwang.aloha.common.Logging


object NettyUtils extends Logging {
  
  private def getPrivateStaticField(name: String) = try {
    val f = PooledByteBufAllocator.DEFAULT.getClass.getDeclaredField(name)
    f.setAccessible(true)
    f.getInt(null)
  } catch {
    case e: Exception =>
      throw new RuntimeException(e)
  }
}