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


Scala SocketChannel类代码示例

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


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

示例1: HttpHandler

//设置package包名称以及导入依赖的类
package org.dsa.iot.scala.netty

import java.util.Map

import collection.JavaConverters.mapAsScalaMapConverter
import util.control.NonFatal

import org.dsa.iot.dslink.provider.HttpProvider
import org.dsa.iot.dslink.util.URLInfo
import org.dsa.iot.dslink.util.http.HttpResp
import org.dsa.iot.shared.SharedObjects

import io.netty.bootstrap.Bootstrap
import io.netty.channel._
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.http._
import io.netty.handler.ssl.SslContextBuilder
import io.netty.handler.ssl.util.InsecureTrustManagerFactory
import io.netty.util.CharsetUtil


private[netty] class HttpHandler extends SimpleChannelInboundHandler[Object] {
  private val content = new StringBuffer
  private var status: HttpResponseStatus = null
  private var t: Throwable = null

  protected def channelRead0(ctx: ChannelHandlerContext, msg: Object) = {
    if (msg.isInstanceOf[HttpResponse])
      status = msg.asInstanceOf[HttpResponse].getStatus
    if (msg.isInstanceOf[HttpContent]) {
      val buf = msg.asInstanceOf[HttpContent].content
      content.append(buf.toString(CharsetUtil.UTF_8))
    }
    if (msg.isInstanceOf[LastHttpContent])
      ctx.close
  }

  override def exceptionCaught(ctx: ChannelHandlerContext, t: Throwable) = {
    this.t = t
    ctx.close
  }

  def getThrowable = t

  def getStatus = status

  def getContent = content.toString
} 
开发者ID:IOT-DSA,项目名称:sdk-dslink-scala,代码行数:50,代码来源:CustomHttpProvider.scala

示例2: upgradeTo

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

import com.twitter.finagle.http
import com.twitter.finagle.Stack
import com.twitter.finagle.netty4.http.exp.{HttpCodecName, initServer}
import com.twitter.logging.Logger
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{Channel, ChannelHandlerContext, ChannelInitializer,
  ChannelInboundHandlerAdapter}
import io.netty.handler.codec.http.HttpServerUpgradeHandler.{
  SourceCodec, UpgradeCodec, UpgradeCodecFactory}
import io.netty.handler.codec.http.{FullHttpRequest, HttpServerUpgradeHandler}
import io.netty.handler.codec.http2.{
  Http2Codec, Http2CodecUtil, Http2ServerDowngrader, Http2ServerUpgradeCodec, Http2ResetFrame}
import io.netty.util.AsciiString

, initializer)) {
          override def upgradeTo(ctx: ChannelHandlerContext, upgradeRequest: FullHttpRequest) {
            // we turn off backpressure because Http2 only works with autoread on for now
            ctx.channel.config.setAutoRead(true)
            super.upgradeTo(ctx, upgradeRequest)
          }

        }
      } else null
    }
  }

  def initChannel(ch: SocketChannel): Unit = {
    val p = ch.pipeline()
    val maxRequestSize = params[http.param.MaxRequestSize].size
    val httpCodec = p.get(HttpCodecName) match {
      case codec: SourceCodec => codec
      case other => // This is very unexpected. Abort and log very loudly
        p.close()
        val msg = s"Unexpected codec found: ${other.getClass.getSimpleName}. " +
          "Aborting channel initialization"
        val ex = new IllegalStateException(msg)
        Logger.get(this.getClass).error(ex, msg)
        throw ex
    }
    p.addAfter(HttpCodecName, "upgradeHandler",
      new HttpServerUpgradeHandler(httpCodec, upgradeCodecFactory, maxRequestSize.inBytes.toInt))

    p.addLast(init)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:48,代码来源:Http2CleartextServerInitializer.scala

示例3: 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

示例4: ConnectHandler

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

import java.net.{InetSocketAddress, UnknownHostException}

import io.netty.bootstrap.Bootstrap
import io.netty.channel._
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import tk.dasb.codec.{ReplyEncoder, ReqDecoder}
import tk.dasb.protocol.{Reply, Req}
import tk.dasb.util.{FutureConv, Log}


class ConnectHandler(val req: Req) extends ChannelInboundHandlerAdapter with Log  with FutureConv{

  var  closeAll: ()=>Any = ()=>{}

  override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = closeAll()

  override def channelInactive(ctx: ChannelHandlerContext): Unit = closeAll()

  override def channelActive(ctx: ChannelHandlerContext): Unit = {

    val b = new Bootstrap
    b.group(ctx.channel.eventLoop).channel(classOf[NioSocketChannel])
      .option[java.lang.Boolean](ChannelOption.SO_KEEPALIVE, true).option[java.lang.Boolean](ChannelOption.TCP_NODELAY, true)
      .handler(new ChannelInitializer[SocketChannel] {
        override def initChannel(ch: SocketChannel): Unit = {}
      })


    log.debug("connecting:{}", req.dstAddress)
    b.connect(req.dstAddress).success{
      connFuture =>
        log.debug("connect success")
        ctx.writeAndFlush(Reply.connSuccess(ctx.channel.localAddress.asInstanceOf[InetSocketAddress])).success{
          writeFuture =>
            closeAll = ()=> {
              ctx.close()
              connFuture.channel().close()
            }
            ctx.pipeline.remove(classOf[ReqDecoder])
            ctx.pipeline.remove(classOf[ReqHandler])
            ctx.pipeline.remove(classOf[ReplyEncoder])
            ctx.pipeline.remove(ConnectHandler.this)
            ctx.pipeline.addLast(new PipHandler(connFuture.channel)) // client -> proxy
            connFuture.channel.pipeline.addFirst(new PipHandler(writeFuture.channel)) // remote -> proxy
        }
    }.failed{
      connFuture=>
        connFuture.cause match {
          case _: UnknownHostException =>
            ctx.writeAndFlush(Reply.failed(req.dstAddress, Reply.FAILURE_HOST_UNREACH)).Close
          case _ =>
            ctx.writeAndFlush(Reply.failed(req.dstAddress, Reply.FAILURE_SERVER)).Close
        }
    }
  }

} 
开发者ID:xqdxqd,项目名称:tiny-sock5-server,代码行数:61,代码来源:ConnectHandler.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: LegacyChannelInitializer

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

import com.wavesplatform.network.{HandshakeDecoder, HandshakeHandler, HandshakeTimeoutHandler, LegacyFrameCodec}
import io.netty.channel.ChannelInitializer
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.{LengthFieldBasedFrameDecoder, LengthFieldPrepender}

import scala.concurrent.duration._

class LegacyChannelInitializer(handshakeHandler: HandshakeHandler) extends ChannelInitializer[SocketChannel] {
  override def initChannel(ch: SocketChannel): Unit =
  ch.pipeline()
    .addLast(
      new HandshakeDecoder,
      new HandshakeTimeoutHandler(30.seconds),
      handshakeHandler,
      new LengthFieldPrepender(4),
      new LengthFieldBasedFrameDecoder(1024*1024, 0, 4, 0, 4),
      new LegacyFrameCodec(NopPeerDatabase))
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:21,代码来源:LegacyChannelInitializer.scala

示例7: InputStreamingChannelInitializer

//设置package包名称以及导入依赖的类
package com.bwsw.sj.engine.input.connection.tcp.server

import java.util.concurrent.ArrayBlockingQueue

import com.bwsw.sj.engine.core.input.InputStreamingExecutor
import io.netty.buffer.ByteBuf
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{ChannelHandlerContext, ChannelInitializer}
import io.netty.handler.codec.string.StringEncoder
import io.netty.handler.logging.{LogLevel, LoggingHandler}

import scala.collection.concurrent


class InputStreamingChannelInitializer(executor: InputStreamingExecutor,
                                       channelContextQueue: ArrayBlockingQueue[ChannelHandlerContext],
                                       bufferForEachContext: concurrent.Map[ChannelHandlerContext, ByteBuf])
  extends ChannelInitializer[SocketChannel] {

  def initChannel(channel: SocketChannel) = {
    val pipeline = channel.pipeline()

    pipeline.addLast("logger", new LoggingHandler(LogLevel.WARN))
    pipeline.addLast("encoder", new StringEncoder())
    pipeline.addLast("handler", new InputStreamingServerHandler(executor, channelContextQueue, bufferForEachContext))
  }
} 
开发者ID:bwsw,项目名称:sj-platform,代码行数:28,代码来源:InputStreamingChannelInitializer.scala

示例8: ServerInitializer

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

import com.bwsw.tstreamstransactionserver.netty.Message
import com.bwsw.tstreamstransactionserver.options.ServerOptions.TransportOptions
import io.netty.buffer.ByteBuf
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{ChannelInitializer, SimpleChannelInboundHandler}
import io.netty.handler.codec.LengthFieldBasedFrameDecoder
import io.netty.handler.codec.bytes.ByteArrayEncoder



class ServerInitializer(serverHandler: => SimpleChannelInboundHandler[ByteBuf]) extends ChannelInitializer[SocketChannel] {
  override def initChannel(ch: SocketChannel): Unit = {
    ch.pipeline()
      .addLast(new ByteArrayEncoder())
      .addLast(new LengthFieldBasedFrameDecoder(
        Int.MaxValue,
        //packageTransmissionOpts.maxDataPackageSize max packageTransmissionOpts.maxMetadataPackageSize,
        Message.headerFieldSize,
        Message.lengthFieldSize)
      )
      .addLast(serverHandler)
  }
} 
开发者ID:bwsw,项目名称:tstreams-transaction-server,代码行数:26,代码来源:ServerInitializer.scala

示例9: ClientInitializer

//设置package包名称以及导入依赖的类
package com.bwsw.tstreamstransactionserver.netty.client

import java.util.concurrent.ConcurrentHashMap

import com.twitter.scrooge.ThriftStruct
import com.bwsw.tstreamstransactionserver.netty.Message
import io.netty.channel.ChannelInitializer
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.LengthFieldBasedFrameDecoder
import io.netty.handler.codec.bytes.ByteArrayEncoder

import scala.concurrent.{ExecutionContext, Promise => ScalaPromise}

class ClientInitializer(reqIdToRep: ConcurrentHashMap[Long, ScalaPromise[ThriftStruct]], client: Client, context: ExecutionContext) extends ChannelInitializer[SocketChannel] {
  override def initChannel(ch: SocketChannel): Unit = {
    ch.pipeline()
      .addLast(new ByteArrayEncoder())
      .addLast(new LengthFieldBasedFrameDecoder(
        Int.MaxValue,
        Message.headerFieldSize,
        Message.lengthFieldSize)
      )
      .addLast(new ClientHandler(reqIdToRep, client, context))
  }
} 
开发者ID:bwsw,项目名称:tstreams-transaction-server,代码行数:26,代码来源:ClientInitializer.scala

示例10: XmppServerInitializer

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

import akka.actor.{ActorSystem, Props}
import com.scxmpp.c2s.C2SManager
import com.scxmpp.cluster.ClusterListener
import com.scxmpp.modules.support.{ModuleManager, HandlerManager}
import com.scxmpp.netty.{XmlElementDecoder, XmlElementEncoder, XmlFrameDecoder}
import com.scxmpp.routing.Router
import com.scxmpp.server.{ServerContext, SslContextHelper}
import com.typesafe.config.Config
import io.netty.channel.socket.SocketChannel
import io.netty.channel.{ChannelInitializer, ChannelPipeline}
import io.netty.handler.codec.string.StringEncoder
import io.netty.util.CharsetUtil

class XmppServerInitializer(context: ServerContext, config: Config) extends ChannelInitializer[SocketChannel] {
  context.actorSystem.actorOf(Props[ClusterListener], "clusterListener")
  context.actorSystem.actorOf(Props(classOf[Router], context, config), "router")
  context.actorSystem.actorOf(Props(classOf[C2SManager], config), "c2s")
  context.actorSystem.actorOf(Props(classOf[ModuleManager], context, config), "module")
  context.actorSystem.actorOf(Props(classOf[HandlerManager], context, config), "handler")

  var sslContext = SslContextHelper.getContext(config)

  override def initChannel(s: SocketChannel): Unit = {
    val p: ChannelPipeline = s.pipeline
    if (sslContext.isDefined)
      p.addLast(sslContext.get.newHandler(s.alloc))
    p.addLast("xmlFrameDecoder", new XmlFrameDecoder())
    p.addLast("xmlElementDecoder", new XmlElementDecoder())
    p.addLast("xmlElementEncoder", new XmlElementEncoder())
    p.addLast("handler", new XmppServerHandler(context.actorSystem))
  }
} 
开发者ID:madprogrammer,项目名称:scxmppd,代码行数:35,代码来源:XmppServerInitializer.scala

示例11: MappedWebServerInitializer

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

import com.scxmpp.server.{ServerContext, SslContextHelper}
import com.typesafe.config.Config
import io.netty.channel.ChannelInitializer
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.http.{HttpObjectAggregator, HttpServerCodec}
import io.netty.handler.stream.ChunkedWriteHandler

class MappedWebServerInitializer(context: ServerContext, config: Config) extends ChannelInitializer[SocketChannel] {
  var sslContext = SslContextHelper.getContext(config)

  override def initChannel(s: SocketChannel): Unit = {
    val p = s.pipeline()
    if (sslContext.isDefined)
      p.addLast(sslContext.get.newHandler(s.alloc))
    p.addLast("codec", new HttpServerCodec())
    p.addLast("aggregator", new HttpObjectAggregator(65536))
    p.addLast("chunked", new ChunkedWriteHandler())
    p.addLast("handler", new MappedWebServerHandler(context, config))
  }
} 
开发者ID:madprogrammer,项目名称:scxmppd,代码行数:23,代码来源:MappedWebServerInitializer.scala

示例12: BoshServerInitializer

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

import akka.actor.Props
import com.scxmpp.netty.XmlElementDecoder
import com.scxmpp.server.{ServerContext, SslContextHelper}
import com.typesafe.config.Config
import io.netty.channel.{ChannelInitializer, ChannelPipeline}
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.http._
import io.netty.handler.stream.ChunkedWriteHandler

class BoshServerInitializer(context: ServerContext, config: Config) extends ChannelInitializer[SocketChannel] {
  var sslContext = SslContextHelper.getContext(config)
  context.actorSystem.actorOf(Props(classOf[BoshConnectionManager], config), "bosh")

  override def initChannel(s: SocketChannel): Unit = {
    val p: ChannelPipeline = s.pipeline
    if (sslContext.isDefined)
      p.addLast(sslContext.get.newHandler(s.alloc))

    // Decoders
    p.addLast("httpDecoder", new HttpRequestDecoder())
    p.addLast("httpEncoder", new HttpResponseEncoder())

    p.addLast("httpAggregator", new HttpObjectAggregator(65536))
    p.addLast("xmlFrameDecoder", new HttpXmlFrameDecoder())
    p.addLast("xmlElementDecoder", new XmlElementDecoder(false))

    // Encoders
    p.addLast("xmlHttpResponseEncoder", new XmlHttpResponseEncoder())
    p.addLast("chunked", new ChunkedWriteHandler())

    // Handler
    p.addLast("handler", new BoshXmppServerHandler(context))
  }
} 
开发者ID:madprogrammer,项目名称:scxmppd,代码行数:37,代码来源:BoshServerInitializer.scala

示例13: onStop

//设置package包名称以及导入依赖的类
package webby.commons.io

import java.net.URI
import java.util.concurrent.TimeUnit

import io.netty.bootstrap.Bootstrap
import io.netty.channel._
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.http._
import webby.api.{Application, Plugin}
import webby.mvc.AppPluginHolder


  override def onStop(): Unit = {
    bootstrap = null
    if (group != null) group.shutdownGracefully(0, 1, TimeUnit.SECONDS)
  }

  def doRequest(req: FullHttpRequest): Unit = {
    require(bootstrap != null, "SimpleAsyncHttpClientPlugin not initialized")
    val uri: URI = new URI(req.uri)
    val port: Int = if (uri.getPort == -1) 80 else uri.getPort
    bootstrap.connect(uri.getHost, port).addListener(new ChannelFutureListener {
      override def operationComplete(future: ChannelFuture): Unit = {
        future.channel().writeAndFlush(req)
      }
    })
  }
}

object SimpleAsyncHttpClient {
  val holder = new AppPluginHolder[SimpleAsyncHttpClientPlugin]()

  def doGetRequest(url: String): Unit = {
    val req: DefaultFullHttpRequest =
      new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, url)
    holder.get.doRequest(req)
  }
} 
开发者ID:citrum,项目名称:webby,代码行数:42,代码来源:SimpleAsyncHttpClientPlugin.scala

示例14: 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

示例15: PortClient

//设置package包名称以及导入依赖的类
package io.dac.mara.ports

import io.netty.bootstrap.Bootstrap
import io.netty.buffer.Unpooled
import io.netty.channel._
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio._
import io.netty.handler.codec.string.{StringDecoder, StringEncoder}
import io.netty.util.CharsetUtil


class PortClient {
  val group = new NioEventLoopGroup()

  def connect(group: EventLoopGroup): ChannelFuture = {
    val bootstrap = new Bootstrap()
      .group(group)
      .channel(classOf[NioSocketChannel])
      .option[java.lang.Boolean](ChannelOption.TCP_NODELAY, true)
      .handler(new ChannelInitializer[SocketChannel]{
        override def initChannel(ch: SocketChannel): Unit = {
          val pipeline = ch.pipeline()
          println("Adding handler to pipeline")
          pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8))
          pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8))
          pipeline.addLast(new PortClientHandler)
        }
      })

    bootstrap.connect("127.0.0.1", 12345).sync()
  }

  def start: Unit = {
    try {
      val future = connect(group)
      val channel = future.channel()

      val message = "D0\"hello, world\""
      val buffer = Unpooled.buffer(message.length)

      message.foreach { ch =>
        buffer.writeByte(ch.toInt)
      }

      channel.writeAndFlush(buffer).sync()

    } finally {
      Thread.sleep(10000)
      group.shutdownGracefully()
      println("Shut down")
    }
  }
}

object PortClient {
  def main(args: Array[String]): Unit = {
    val client = new PortClient
    client.start
  }
} 
开发者ID:dacjames,项目名称:mara2-lang,代码行数:62,代码来源:PortClient.scala


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