当前位置: 首页>>代码示例>>Scala>>正文


Scala Channel类代码示例

本文整理汇总了Scala中io.netty.channel.Channel的典型用法代码示例。如果您正苦于以下问题:Scala Channel类的具体用法?Scala Channel怎么用?Scala Channel使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Channel类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: NpnOrAlpnHandler

//设置package包名称以及导入依赖的类
package com.twitter.finagle.http2.transport

import com.twitter.finagle.Stack
import com.twitter.finagle.netty4.http.exp._
import io.netty.channel.{Channel, ChannelHandlerContext, ChannelInitializer}
import io.netty.handler.codec.http2.{Http2Codec, Http2ServerDowngrader}
import io.netty.handler.ssl.{ApplicationProtocolNames, ApplicationProtocolNegotiationHandler}

private[http2] class NpnOrAlpnHandler(init: ChannelInitializer[Channel], params: Stack.Params)
  extends ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

  @throws(classOf[Exception])
  protected def configurePipeline(ctx: ChannelHandlerContext, protocol: String) {

    protocol match {
      case ApplicationProtocolNames.HTTP_2 =>
        // Http2 has been negotiated, replace the HttpCodec with an Http2Codec
        val initializer = new ChannelInitializer[Channel] {
          def initChannel(ch: Channel): Unit = {
            ch.pipeline.addLast(new Http2ServerDowngrader(false  , initializer))

      case ApplicationProtocolNames.HTTP_1_1 =>
      // The Http codec is already in the pipeline, so we are good!
      case _ =>
        throw new IllegalStateException("unknown protocol: " + protocol)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:29,代码来源:NpnOrAlpnHandler.scala

示例2: Http2TlsServerInitializer

//设置package包名称以及导入依赖的类
package com.twitter.finagle.http2

import com.twitter.finagle.Stack
import com.twitter.finagle.http2.transport.NpnOrAlpnHandler
import io.netty.channel.{Channel, ChannelInitializer}
import io.netty.channel.socket.SocketChannel


private[http2] class Http2TlsServerInitializer (
    init: ChannelInitializer[Channel],
    params: Stack.Params)
  extends ChannelInitializer[SocketChannel] {

  def initChannel(ch: SocketChannel): Unit = {
    val p = ch.pipeline()
    p.addLast(new NpnOrAlpnHandler(init, params))
    p.addLast(init)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:20,代码来源:Http2TlsServerInitializer.scala

示例3: ServerBridge

//设置package包名称以及导入依赖的类
package com.twitter.finagle.netty4.channel

import com.twitter.finagle.transport.Transport
import io.netty.channel.{ChannelInitializer, Channel}
import io.netty.channel.ChannelHandler.Sharable


@Sharable
private[netty4] class ServerBridge[In, Out](
    transportFac: Channel => Transport[In, Out],
    serveTransport: Transport[In, Out] => Unit)
  extends ChannelInitializer[Channel] {

  def initChannel(ch: Channel): Unit = {
    val transport: Transport[In, Out] = transportFac(ch)
    serveTransport(transport)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:19,代码来源:ServerBridge.scala

示例4: RichChannelFuture

//设置package包名称以及导入依赖的类
package tk.dasb.util

import io.netty.channel.{Channel, ChannelFuture, ChannelFutureListener}


trait FutureConv {

  implicit class RichChannelFuture(val ch: ChannelFuture) {

    def success[T](block: ChannelFuture => T): ChannelFuture = {
      ch.addListener(new ChannelFutureListener {
        override def operationComplete(future: ChannelFuture): Unit = if (future.isSuccess) block(future)
      })
    }

    def failed[T](block: ChannelFuture => T): ChannelFuture = {
      ch.addListener(new ChannelFutureListener {
        override def operationComplete(future: ChannelFuture): Unit = if (!future.isSuccess) block(future)
      })
    }

    def Close(): ChannelFuture = {
      ch.addListener(ChannelFutureListener.CLOSE)
    }

    def failedClose(): ChannelFuture = {
      ch.addListener(ChannelFutureListener.CLOSE_ON_FAILURE)
    }

    def callBack[P >: ChannelFuture, T](block: P => T): ChannelFuture = {
      ch.addListener(new ChannelFutureListener {
        override def operationComplete(future: ChannelFuture): Unit = block(future)
      })
    }
  }


} 
开发者ID:xqdxqd,项目名称:tiny-sock5-server,代码行数:39,代码来源:FutureConv.scala

示例5: inetSocketAddress

//设置package包名称以及导入依赖的类
package com.wavesplatform

import java.net.{InetSocketAddress, SocketAddress, URI}
import java.util.concurrent.Callable

import com.wavesplatform.state2.ByteStr
import io.netty.channel.group.{ChannelGroup, ChannelMatchers}
import io.netty.channel.local.LocalAddress
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{Channel, ChannelHandlerContext}
import io.netty.util.NetUtil.toSocketAddressString
import io.netty.util.concurrent.{EventExecutorGroup, ScheduledFuture}
import scorex.block.Block
import scorex.utils.ScorexLogging

import scala.concurrent.duration._

package object network extends ScorexLogging {
  def inetSocketAddress(addr: String, defaultPort: Int): InetSocketAddress = {
    val uri = new URI(s"node://$addr")
    if (uri.getPort < 0) new InetSocketAddress(addr, defaultPort)
    else new InetSocketAddress(uri.getHost, uri.getPort)
  }

  implicit class EventExecutorGroupExt(val e: EventExecutorGroup) extends AnyVal {
    def scheduleWithFixedDelay(initialDelay: FiniteDuration, delay: FiniteDuration)(f: => Unit): ScheduledFuture[_] =
      e.scheduleWithFixedDelay((() => f): Runnable, initialDelay.toNanos, delay.toNanos, NANOSECONDS)

    def schedule[A](delay: FiniteDuration)(f: => A): ScheduledFuture[A] =
      e.schedule((() => f): Callable[A], delay.length, delay.unit)
  }

  private def formatAddress(sa: SocketAddress) = sa match {
    case null => ""
    case l: LocalAddress => s" ${l.toString}"
    case isa: InetSocketAddress => s" ${toSocketAddressString(isa)}"
  }

  def id(ctx: ChannelHandlerContext): String = id(ctx.channel())

  def id(chan: Channel, prefix: String = ""): String = s"[$prefix${chan.id().asShortText()}${formatAddress(chan.remoteAddress())}]"

  def formatBlocks(blocks: Seq[Block]): String = formatSignatures(blocks.view.map(_.uniqueId))

  def formatSignatures(signatures: Seq[ByteStr]): String = if (signatures.isEmpty) ""
    else if (signatures.size == 1) s"[${signatures.head}]"
    else s"[${signatures.head}..${signatures.last}]"

  implicit class ChannelHandlerContextExt(val ctx: ChannelHandlerContext) extends AnyVal {
    def remoteAddress: InetSocketAddress = ctx.channel().asInstanceOf[SocketChannel].remoteAddress()
  }

  implicit class ChannelGroupExt(val allChannels: ChannelGroup) extends AnyVal {
    def broadcast(message: AnyRef, except: Option[Channel] = None): Unit = {
      log.trace(s"Broadcasting $message to ${allChannels.size()} channels${except.fold("")(c => s" (except ${id(c)})")}")
      allChannels.writeAndFlush(message, except.fold(ChannelMatchers.all())(ChannelMatchers.isNot))
    }
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:60,代码来源:package.scala

示例6: NettyScalaFuture

//设置package包名称以及导入依赖的类
package com.wavesplatform.it

import java.util.concurrent.CancellationException

import io.netty.channel.{Channel, ChannelFuture}

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

package object network {
  implicit class NettyScalaFuture(nettyFuture: ChannelFuture) {
    def asScala: Future[Channel] = {
      val p = Promise[Channel]()
      nettyFuture.addListener((future: ChannelFuture) => p complete Try(
        if (future.isSuccess) future.channel()
        else if (future.isCancelled) throw new CancellationException
        else throw future.cause()))
      p.future
    }
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:22,代码来源:package.scala

示例7: NettyFutureConverters

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal

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

import scala.concurrent.{ Future, 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
    }
  }

} 
开发者ID:lagom,项目名称:lagom,代码行数:47,代码来源:NettyFutureConverters.scala

示例8: Server

//设置package包名称以及导入依赖的类
package com.scxmpp.server

import java.net.InetSocketAddress

import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.PooledByteBufAllocator
import io.netty.channel.epoll.{Epoll, EpollEventLoopGroup, EpollServerSocketChannel}
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.channel.{Channel, ChannelOption, EventLoopGroup, ServerChannel, ChannelInitializer}

import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer
import com.typesafe.config.Config

class Server(context: ServerContext) {

  var channels = ArrayBuffer.empty[Channel]
  var bootstraps = ArrayBuffer.empty[ServerBootstrap]

  private def doRun(group: EventLoopGroup, clazz: Class[_ <: ServerChannel]): Unit = {
    try {
      for(server <- context.servers) {
        val bootstrap = new ServerBootstrap()
        bootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true))
        val initializer = context.dynamicAccess.createInstanceFor[ChannelInitializer[Channel]](
          server.getString("module"), List(classOf[ServerContext] -> context, classOf[Config] -> server)).get
        bootstrap.group(group).channel(clazz).childHandler(initializer)

        val inet: InetSocketAddress = new InetSocketAddress(
          server.getString("endpoint.address"), server.getInt("endpoint.port"))
        channels.add(bootstrap.bind(inet).sync.channel)
      }
    } finally {
      for (channel <- channels)
        channel.closeFuture.sync
      group.shutdownGracefully.sync
    }
  }

  def run(): Unit = {
    if (Epoll.isAvailable) {
      doRun(new EpollEventLoopGroup, classOf[EpollServerSocketChannel])
    }
    else {
      doRun(new NioEventLoopGroup, classOf[NioServerSocketChannel])
    }
  }
} 
开发者ID:madprogrammer,项目名称:scxmppd,代码行数:50,代码来源:Server.scala

示例9: NettyHttpServer

//设置package包名称以及导入依赖的类
package woshilaiceshide.sserver.benchmark.netty

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.example.http.helloworld.HttpHelloWorldServerHandler
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.channel.socket.nio.NioServerSocketChannel

object NettyHttpServer extends App with woshilaiceshide.sserver.benchmark.ServerProperty {

  class HttpHelloWorldServerInitializer extends ChannelInitializer[SocketChannel] {

    override def initChannel(ch: SocketChannel) {
      //ch.config().setAllowHalfClosure(true)
      val p = ch.pipeline();
      p.addLast(new HttpServerCodec());
      p.addLast(new HttpHelloWorldServerHandler());
    }
  }

  val bossGroup: EventLoopGroup = new NioEventLoopGroup(1);
  val workerGroup: EventLoopGroup = new NioEventLoopGroup(2);
  try {

    val b = new ServerBootstrap();
    b.option[java.lang.Integer](ChannelOption.SO_BACKLOG, 1024);
    b.group(bossGroup, workerGroup).channel(classOf[NioServerSocketChannel]).childHandler(new HttpHelloWorldServerInitializer());

    val ch: Channel = b.bind(interface, port).sync().channel();

    //??? just check for ipv4
    System.err.println(s"Open your web browser and navigate to http://${if ("0.0.0.0" == interface) "127.0.0.1" else interface}:${port}/");

    ch.closeFuture().sync();
  } finally {
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
  }

} 
开发者ID:woshilaiceshide,项目名称:s-server-benchmark,代码行数:47,代码来源:NettyHttpServer.scala

示例10: inetSocketAddress

//设置package包名称以及导入依赖的类
package com.wavesplatform

import java.net.{InetSocketAddress, SocketAddress, URI}
import java.util.concurrent.Callable

import io.netty.channel.group.{ChannelGroup, ChannelMatchers}
import io.netty.channel.local.LocalAddress
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{Channel, ChannelHandlerContext}
import io.netty.util.NetUtil.toSocketAddressString
import io.netty.util.concurrent.{EventExecutorGroup, ScheduledFuture}
import scorex.utils.ScorexLogging

import scala.concurrent.duration._

package object network extends ScorexLogging {
  def inetSocketAddress(addr: String, defaultPort: Int): InetSocketAddress = {
    val uri = new URI(s"node://$addr")
    if (uri.getPort < 0) new InetSocketAddress(addr, defaultPort)
    else new InetSocketAddress(uri.getHost, uri.getPort)
  }

  implicit class EventExecutorGroupExt(val e: EventExecutorGroup) extends AnyVal {
    def scheduleWithFixedDelay(initialDelay: FiniteDuration, delay: FiniteDuration)(f: => Unit): ScheduledFuture[_] =
      e.scheduleWithFixedDelay((() => f): Runnable, initialDelay.toNanos, delay.toNanos, NANOSECONDS)

    def schedule[A](delay: FiniteDuration)(f: => A): ScheduledFuture[A] =
      e.schedule((() => f): Callable[A], delay.length, delay.unit)
  }

  private def formatAddress(sa: SocketAddress) = sa match {
    case null => ""
    case l: LocalAddress => s" ${l.toString}"
    case isa: InetSocketAddress => s" ${toSocketAddressString(isa)}"
  }

  def id(ctx: ChannelHandlerContext): String = id(ctx.channel())

  def id(chan: Channel): String = s"[${chan.id().asShortText()}${formatAddress(chan.remoteAddress())}]"

  implicit class ChannelHandlerContextExt(val ctx: ChannelHandlerContext) extends AnyVal {
    def remoteAddress: InetSocketAddress = ctx.channel().asInstanceOf[SocketChannel].remoteAddress()
  }

  implicit class ChannelExt(val channel: Channel) extends AnyVal {
    def declaredAddress: Option[InetSocketAddress] = Option(channel.attr(AttributeKeys.DeclaredAddress).get())
  }

  implicit class ChannelGroupExt(val allChannels: ChannelGroup) extends AnyVal {
    def broadcast(message: AnyRef, except: Option[Channel] = None): Unit = {
      log.trace(s"Broadcasting $message to ${allChannels.size()} channels${except.fold("")(c => s" (except ${id(c)})")}")
      allChannels.writeAndFlush(message, except.fold(ChannelMatchers.all())(ChannelMatchers.isNot))
    }
  }

} 
开发者ID:mikepijn,项目名称:wavesnode,代码行数:57,代码来源:package.scala


注:本文中的io.netty.channel.Channel类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。