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


Scala InetSocketAddress类代码示例

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


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

示例1: beforeAll

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

import java.net.InetSocketAddress

import com.twitter.finagle
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Future
import org.scalatest._
import placeholder.Main

import scala.concurrent.Await
import scala.concurrent.duration._

trait IntegrationTestBase extends FeatureSpec with GivenWhenThen with Matchers with BeforeAndAfterAll {
  val server = Main

  var serverAddress: InetSocketAddress = _
  var client: Service[Request, Response] = _
  var requestHost: String = _

  server.main(Array())

  override def beforeAll(): Unit = {
    serverAddress = Await.result(server.getServerAddress, 10.seconds)
    requestHost = s"localhost:${serverAddress.getPort.toString}"
    client = finagle.Http.newService(requestHost)
  }

  def performRequest(request: Request): Future[Response] = {
    request.host = requestHost
    client(request)
  }
} 
开发者ID:scala-academy,项目名称:skeleton-project,代码行数:35,代码来源:IntegrationTestBase.scala

示例2: EmberRunner

//设置package包名称以及导入依赖的类
import java.io.File
import java.net.InetSocketAddress

import play.sbt.PlayRunHook
import sbt._

object EmberRunner {
  def apply(logger: Logger,
            baseDir: File,
            port: Int = 4200): PlayRunHook = {

    object EmberRunHook extends PlayRunHook {
      var watchProcess: Option[Process] = None

      override def beforeStarted(): Unit = {
        if (baseDir.exists()) {
          logger.info("Executing npm install")
          val npm = Process(Seq("npm", "install"), baseDir).lines
          npm.foreach(logger.info(_))

          logger.info("Executing bower install")
          val bower = Process(Seq("bower", "install"), baseDir).lines
          bower.foreach(logger.info(_))
        } else {
          logger.info(s"Skipping npm and bower install. UI application directory ${baseDir.getAbsolutePath} not found.")
        }
      }

      override def afterStarted(addr: InetSocketAddress): Unit = {
        addr.getAddress.getHostAddress
        val url = s"http://localhost:${addr.getPort}"
        if (baseDir.exists()) {
          logger.info(s"Starting ember server in development mode. Setting proxy to $url")
          watchProcess = Some(Process(Seq("ember", "serve", "--proxy", url, "--port", port.toString), baseDir).run(logger))
        } else {
          logger.info(s"Skipping ember server start. UI application directory ${baseDir.getAbsolutePath} not found.")
        }
      }

      override def afterStopped(): Unit = {
        logger.info("Attempting to stop ember server")
        watchProcess.foreach(_.destroy())
        watchProcess = None
      }
    }
    EmberRunHook
  }
} 
开发者ID:dipayanb,项目名称:play-ember-seed,代码行数:49,代码来源:EmberRunner.scala

示例3: EmbeddedZookeeper

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

import java.io.File
import java.net.InetSocketAddress

import kafka.utils.Utils
import org.apache.zookeeper.server.{NIOServerCnxnFactory, ZooKeeperServer}


class EmbeddedZookeeper(zkPort: Int, zkSnapshotDir: File, zkLogDir: File, autoStart: Boolean) {

  val connectString = s"127.0.0.1:${zkPort}"
  val tickTime = 500
  val factory = new NIOServerCnxnFactory()
  val maxZkConnections = 100
  factory.configure(new InetSocketAddress("127.0.0.1", zkPort), maxZkConnections)

  var zookeeper: ZooKeeperServer = null

  def this(port: Int, autoStart: Boolean = true) = this(port, TestUtils.tempDir, TestUtils.tempDir, autoStart)

  if (autoStart) {
    start()
  }

  def start(): Unit = {
    // With Zookeeper 3.4, the startup logic of the ZookeeperServer has changed where a sequence of:
    // zookeeper.start() -> zookeeper.shutdown() -> zookeeper.start()
    // will fail to restart the ZookeeperServer. Because of this, a new ZookeeperServer needs to be instantiated if
    // we want to simulate Zookeeper unavailability during tests
    zookeeper = new ZooKeeperServer(zkSnapshotDir, zkLogDir, tickTime)
    factory.startup(zookeeper)
  }

  def stop(): Unit = {
    zookeeper.shutdown()
    zookeeper = null
  }

  def snapshotDir: File = zkSnapshotDir

  def logDir: File = zkLogDir

  def cleanShutdown(): Unit = {
    shutdown()
    Utils.rm(zkLogDir)
    Utils.rm(zkSnapshotDir)
  }

  def shutdown(): Unit = {
    Utils.swallow(zookeeper.shutdown())
    Utils.swallow(factory.shutdown())
    zookeeper = null
  }
} 
开发者ID:groupon,项目名称:baryon,代码行数:56,代码来源:EmbeddedZookeeper.scala

示例4: Metrics

//设置package包名称以及导入依赖的类
package eu.inn.kafka.mimic

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

import com.codahale.metrics.graphite.{Graphite, GraphiteReporter}
import nl.grons.metrics.scala.{InstrumentedBuilder, MetricName}

object Metrics extends Logging {
  val metricRegistry = new com.codahale.metrics.MetricRegistry()

  def startReporter(host: String, port: Int, prefix: String, reportPeriod: Long) = {

    val graphite = new Graphite(new InetSocketAddress(host, port))

    val reporter = GraphiteReporter.forRegistry(metricRegistry)
      .prefixedWith(prefix + "." + InetAddress.getLocalHost.getHostName.replaceAll("\\.", "-"))
      .build(graphite)

    new Timer("graphite-reporter-timer").schedule(
      new TimerTask { def run() = reporter.report() },
      reportPeriod,
      reportPeriod
    )
  }
}

trait Metrics extends InstrumentedBuilder {
  override lazy val metricBaseName = MetricName("kafka-mimic")

  lazy val metricRegistry = Metrics.metricRegistry
}

trait MetricsComponent extends Metrics with Logging {

  this: ConfigComponent =>

  def startMetricsReporting() = {
    if (config.hasPath("enabled") && config.getBoolean("enabled")) {
      val host = config.getString("host")
      val port = config.getInt("port")
      log.info(s"Starting graphite reporter for $host:$port")
      Metrics.startReporter(
        host,
        port,
        config.getString("prefix"),
        config.getDuration("report-period", TimeUnit.MILLISECONDS)
      )
    }

    metrics.gauge("heartbeat") { 1 }
  }
} 
开发者ID:InnovaCo,项目名称:kafka-mimic,代码行数:55,代码来源:Metrics.scala

示例5: UdpAssociationHandle

//设置package包名称以及导入依赖的类
package akka.remote.transport.netty

import akka.actor.Address
import akka.remote.transport.AssociationHandle
import akka.remote.transport.AssociationHandle.{ HandleEventListener, InboundPayload }
import akka.remote.transport.Transport.AssociationEventListener
import akka.util.ByteString
import java.net.{ SocketAddress, InetAddress, InetSocketAddress }
import org.jboss.netty.buffer.{ ChannelBuffer, ChannelBuffers }
import org.jboss.netty.channel._
import scala.concurrent.{ Future, Promise }


private[remote] class UdpAssociationHandle(val localAddress: Address,
                                           val remoteAddress: Address,
                                           private val channel: Channel,
                                           private val transport: NettyTransport) extends AssociationHandle {

  override val readHandlerPromise: Promise[HandleEventListener] = Promise()

  override def write(payload: ByteString): Boolean = {
    if (!channel.isConnected)
      channel.connect(new InetSocketAddress(InetAddress.getByName(remoteAddress.host.get), remoteAddress.port.get))

    if (channel.isWritable && channel.isOpen) {
      channel.write(ChannelBuffers.wrappedBuffer(payload.asByteBuffer))
      true
    } else false
  }

  override def disassociate(): Unit = try channel.close()
  finally transport.udpConnectionTable.remove(transport.addressToSocketAddress(remoteAddress))

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:35,代码来源:UdpSupport.scala

示例6: DaemonicSpec

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

import akka.testkit._
import scala.concurrent.duration._
import akka.actor.{ Address, ExtendedActorSystem, ActorSystem }
import com.typesafe.config.ConfigFactory
import java.nio.channels.ServerSocketChannel
import java.net.InetSocketAddress
import scala.collection.JavaConverters._

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class DaemonicSpec extends AkkaSpec {

  def addr(sys: ActorSystem, proto: String) =
    sys.asInstanceOf[ExtendedActorSystem].provider.getExternalAddressFor(Address(s"akka.$proto", "", "", 0)).get

  def unusedPort = {
    val ss = ServerSocketChannel.open().socket()
    ss.bind(new InetSocketAddress("localhost", 0))
    val port = ss.getLocalPort
    ss.close()
    port
  }

  "Remoting configured with daemonic = on" must {

    "shut down correctly after getting connection refused" in {
      // get all threads running before actor system i started
      val origThreads: Set[Thread] = Thread.getAllStackTraces().keySet().asScala.to[Set]
      // create a separate actor system that we can check the threads for
      val daemonicSystem = ActorSystem("daemonic", ConfigFactory.parseString("""
        akka.daemonic = on
        akka.actor.provider = "akka.remote.RemoteActorRefProvider"
        akka.remote.netty.tcp.transport-class = "akka.remote.transport.netty.NettyTransport"
        akka.remote.netty.tcp.port = 0
        akka.log-dead-letters-during-shutdown = off
      """))

      val unusedAddress = addr(daemonicSystem, "tcp").copy(port = Some(unusedPort))
      val selection = daemonicSystem.actorSelection(s"${unusedAddress}/user/SomeActor")
      selection ! "whatever"
      Thread.sleep(2.seconds.dilated.toMillis)

      // get new non daemonic threads running
      val newNonDaemons: Set[Thread] = Thread.getAllStackTraces().keySet().asScala.seq.
        filter(t ? !origThreads(t) && t.isDaemon == false).to[Set]

      newNonDaemons should be(Set.empty[Thread])
      shutdown(daemonicSystem)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:53,代码来源:DaemonicSpec.scala

示例7: ControllerSpec

//设置package包名称以及导入依赖的类
package akka.remote.testconductor

import akka.testkit.AkkaSpec
import akka.actor.{ PoisonPill, Props, AddressFromURIString }
import akka.testkit.ImplicitSender
import akka.remote.testconductor.Controller.NodeInfo
import java.net.InetSocketAddress
import java.net.InetAddress

object ControllerSpec {
  val config = """
    akka.testconductor.barrier-timeout = 5s
    akka.actor.provider = akka.remote.RemoteActorRefProvider
    akka.actor.debug.fsm = on
    akka.actor.debug.lifecycle = on
    """
}

class ControllerSpec extends AkkaSpec(ControllerSpec.config) with ImplicitSender {

  val A = RoleName("a")
  val B = RoleName("b")

  "A Controller" must {

    "publish its nodes" in {
      val c = system.actorOf(Props(classOf[Controller], 1, new InetSocketAddress(InetAddress.getLocalHost, 0)))
      c ! NodeInfo(A, AddressFromURIString("akka://sys"), testActor)
      expectMsg(ToClient(Done))
      c ! NodeInfo(B, AddressFromURIString("akka://sys"), testActor)
      expectMsg(ToClient(Done))
      c ! Controller.GetNodes
      expectMsgType[Iterable[RoleName]].toSet should be(Set(A, B))
      c ! PoisonPill // clean up so network connections don't accumulate during test run
    }

  }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:40,代码来源:ControllerSpec.scala

示例8: Webpack

//设置package包名称以及导入依赖的类
import java.net.InetSocketAddress

import play.sbt.PlayRunHook
import sbt._

object Webpack {
  def apply(base: File): PlayRunHook = {
    object WebpackHook extends PlayRunHook {
      var process: Option[Process] = None

      override def beforeStarted() = {
        process = Option(
          Process("webpack", base).run()
        )
      }

      override def afterStarted(addr: InetSocketAddress) = {
        process = Option(
          Process("webpack --watch", base).run()
        )
      }

      override def afterStopped() = {
        process.foreach(_.destroy())
        process = None
      }
    }

    WebpackHook
  }
} 
开发者ID:dehora,项目名称:outland-deck,代码行数:32,代码来源:Webpack.scala

示例9: ClientMain

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

import java.net.InetSocketAddress

import akka.actor.{ActorSystem, Props}
import chatapp.client.ClientMessage.SendMessage


object ClientMain extends App {

  val Port = 18573

  val system = ActorSystem("ClientMain")
  val clientConnection = system.actorOf(Props(new ClientActor(new InetSocketAddress("localhost", Port), system)))
  val bufferedReader = io.Source.stdin.bufferedReader()
  loop("")

  def loop(message: String): Boolean = message match {
    case "~quit" =>
      system.terminate()
      false
    case _ =>
      val msg = bufferedReader.readLine()
      clientConnection ! SendMessage(msg)
      loop(msg)
  }
} 
开发者ID:nbokmans,项目名称:7l7wScala,代码行数:28,代码来源:ClientMain.scala

示例10: ClientActor

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

import java.net.InetSocketAddress

import akka.actor.{Actor, ActorSystem, Kill}
import akka.io.Tcp._
import akka.io.{IO, Tcp}
import akka.util.ByteString
import chatapp.client.ClientMessage.SendMessage


class ClientActor(address: InetSocketAddress, actorSystem: ActorSystem) extends Actor {

  IO(Tcp)(actorSystem) ! Connect(address)

  def receive = {
    case CommandFailed(command: Tcp.Command) =>
      println("Failed to connect to " + address.toString)
      self ! Kill
      actorSystem.terminate()
    case Connected(remote, local) =>
      println("Successfully connected to " + address)
      val connection = sender()
      connection ! Register(self)
      context become {
        case Received(data) =>
          println(data.decodeString("US-ASCII"))
        case SendMessage(message) =>
          connection ! Write(ByteString(message))
      }
  }
} 
开发者ID:nbokmans,项目名称:7l7wScala,代码行数:33,代码来源:ClientActor.scala

示例11: GameServer

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

import java.net.InetSocketAddress

import akka.actor._
import akka.io.Tcp.Bind
import akka.io.{IO, Tcp}

class GameServer(handlerProps: (ActorRef, InetSocketAddress) => Props)
  extends Actor with ActorLogging {

  import Tcp._

  override def receive: Receive = {
    case [email protected](localAddress) => log.debug("Bound server to {}.", localAddress)
    case [email protected](cmd) =>
      log.error("Command {} failed so closing server.", cmd)
      context stop self
    case [email protected](remote, local) =>
      val connection = sender()
      val handler = context.actorOf(handlerProps(connection, remote))
      connection ! Register(handler)
  }
}

class GameServerFactory(host: String, port: Int, handlerProps: (ActorRef, InetSocketAddress) => Props)
                       (implicit system: ActorSystem) extends GameEndPoint {
  override val connectionString: String = host + ":" + port

  val server = system.actorOf(Props(classOf[GameServer], handlerProps))

  override def init(): Unit = {
    IO(Tcp) ! Bind(server, new InetSocketAddress(host, port))
  }
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:36,代码来源:GameServer.scala

示例12: ServerActor

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

import java.net.InetSocketAddress

import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.io.Tcp

object ServerActor {
  def props(bindAddress: InetSocketAddress, tcp: ActorRef, handler:ActorRef) =
    Props(classOf[ServerActor], bindAddress, tcp, handler)
}

class ServerActor(bindAddress: InetSocketAddress, tcp: ActorRef, handler: ActorRef) extends Actor with ActorLogging {
  import Tcp._

  // TODO: verify why we bind from within the actor
 tcp ! Bind(self, bindAddress)

  def receive = {
    case b @ Bound(localAddress) =>
      log.info(s"Tcp Server bound to <$localAddress>")

    case CommandFailed(_: Bind) =>
      log.warning("Tcp ServerActor failed to bind. Stopping...")
      context stop self

    case c @ Connected(remote, local) =>
      log.info(s"Tcp Server Connected. remote=<$remote>, local=<$local>. Registering handler...")
      val connection = sender()
      connection ! Register(handler)
  }
} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:33,代码来源:ServerActor.scala

示例13: ClientActor

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

import akka.actor.{ Actor, ActorRef, Props }
import akka.io.Tcp
import akka.util.ByteString
import java.net.InetSocketAddress

object ClientActor {
  def props(remote: InetSocketAddress, tcp: ActorRef, replies: ActorRef) =
    Props(classOf[ClientActor], remote, tcp, replies)
}

class ClientActor(remote: InetSocketAddress, tcp:ActorRef, listener: ActorRef) extends Actor {
  import Tcp._
  import context.system

  tcp ! Connect(remote)

  def receive = {
    case CommandFailed(_: Connect) =>
      listener ! "connect failed"
      context stop self

    case c @ Connected(remote, local) =>
      listener ! c
      val connection = sender()
      connection ! Register(self)
      context become {
        case data: ByteString =>
          connection ! Write(data)
        case CommandFailed(w: Write) =>
          // O/S buffer was full
          listener ! "write failed"
        case Received(data) =>
          listener ! data
        case "close" =>
          connection ! Close
        case _: ConnectionClosed =>
          listener ! "connection closed"
          context stop self
      }
  }
} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:44,代码来源:ClientActor.scala

示例14: Client

//设置package包名称以及导入依赖的类
package wow.common.network

import java.net.InetSocketAddress

import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.io.{IO, Tcp}
import akka.util.ByteString


object Client {
  def props(remote: InetSocketAddress, listener: ActorRef) = Props(classOf[Client], remote, listener)
}


class Client(remote: InetSocketAddress, listener: ActorRef) extends Actor with ActorLogging {

  import akka.io.Tcp._
  import context.system

  IO(Tcp) ! Connect(remote)

  def receive: PartialFunction[Any, Unit] = {
    case CommandFailed(_: Connect) =>
      listener ! "connect failed"
      context stop self

    case [email protected](dist, local) =>
      log.debug("[CLIENT] Connected from: " + local + " to: " + dist)
      listener ! c
      val connection = sender()
      connection ! Register(self)
      context become {
        case 42 => sender() ! 42
        case data: ByteString =>
          log.debug("[CLIENT] Sent : " + data)
          connection ! Write(data)
        case CommandFailed(_: Write) =>
          // O/S buffer was full
          listener ! "write failed"
        case Received(data) =>
          log.debug("[CLIENT] Received : " + data)
          listener ! data
        case "close" =>
          connection ! Close
        case _: ConnectionClosed =>
          listener ! "connection closed"
          context stop self
      }
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:51,代码来源:Client.scala

示例15: NioServerEndpoint

//设置package包名称以及导入依赖的类
package knot.remote.endpoints

import java.net.InetSocketAddress
import java.nio.channels.SelectionKey

import knot.remote.channel.{NioChannel, NioServerSocketChannel, NioSocketChannel}

class NioServerEndpoint extends NioEndpoint {

  override def processKey(key: SelectionKey, channel: NioSocketChannel): Unit = {
    if (key.isValid && (key.isReadable || key.readyOps() == 0)) {
      channel.read()
    }
  }

  override def processKey(key: SelectionKey, channel: NioServerSocketChannel): Unit = {
    if (key.isAcceptable) {
      log.debug("SERVER: New Connection")
      val c = channel.accept
      c.register(this, SelectionKey.OP_READ)
    }
  }

  override def init(channel: NioChannel, address: InetSocketAddress): Unit = {
    channel.bind(address)
    channel.register(this, SelectionKey.OP_ACCEPT)
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:29,代码来源:NioServerEndpoint.scala


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