本文整理汇总了Scala中akka.io.IO类的典型用法代码示例。如果您正苦于以下问题:Scala IO类的具体用法?Scala IO怎么用?Scala IO使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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))
}
}
}
示例2: 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))
}
}
示例3: ServerApp
//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.io.IO
import io.prediction.controller.Engine
import io.prediction.data.storage.EngineManifest
import io.prediction.workflow.{CreateServer, ServerConfig, WorkflowUtils}
import spray.can.Http
import spray.can.server.ServerSettings
object ServerApp extends App {
val port = sys.env.getOrElse("PORT", "8000").toInt
val eventServerIp = sys.env.getOrElse("EVENT_SERVER_IP", "localhost")
val eventServerPort = sys.env.getOrElse("EVENT_SERVER_PORT", "7070").toInt
val maybeAccessKey = sys.env.get("ACCESS_KEY")
val maybeLatestEngineInstance = CreateServer.engineInstances.getLatestCompleted(EngineConfig.engineId, EngineConfig.engineVersion, EngineConfig.engineVariantId)
maybeLatestEngineInstance.map { engineInstance =>
// the spark config needs to be set in the engineInstance
engineInstance.copy(sparkConf = engineInstance.sparkConf.updated("spark.master", "local"))
}.fold {
println("Could not get latest completed engine instance")
} { engineInstance =>
val sc = ServerConfig(
engineInstanceId = engineInstance.id,
engineId = Some(engineInstance.engineId),
engineVersion = Some(engineInstance.engineVersion),
engineVariant = EngineConfig.engineVariant,
port = port,
eventServerIp = eventServerIp,
eventServerPort = eventServerPort,
accessKey = maybeAccessKey
)
val (engineLanguage, engineFactory) = WorkflowUtils.getEngine(engineInstance.engineFactory, getClass.getClassLoader)
val engine = engineFactory()
// WTF: The list of files must be at least 2 long due to https://github.com/PredictionIO/PredictionIO/blob/v0.9.6/core/src/main/twirl/io/prediction/workflow/index.scala.html#L56
val manifest = EngineManifest(engineInstance.engineId, engineInstance.engineVersion, "default", None, Seq("WHAT", "THE"), engineInstance.engineFactory)
val actor = CreateServer.createServerActorWithEngine(
sc,
engineInstance,
engine.asInstanceOf[Engine[_, _, _, _, _, _]],
engineLanguage,
manifest
)
val actorSystem = ActorSystem("pio-server")
val settings = ServerSettings(actorSystem)
IO(Http)(actorSystem) ! Http.Bind(listener = actor, interface = sc.ip, port = sc.port)
actorSystem.awaitTermination()
}
}
示例4: BootApp
//设置package包名称以及导入依赖的类
package org.packtpublishing
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.event.Logging
import spray.can.Http
import org.packtpublishing.service.PersistenceService
import org.packtpublishing.web.BookRestService
import org.packtpublishing.security.SslSupport
object BootApp extends App with SslSupport {
import scala.concurrent.ExecutionContext.Implicits.global
implicit val system = ActorSystem("spray-intro")
val log = Logging(system, getClass)
val persistence = new PersistenceService
persistence.createSchema() onSuccess {
case _ => persistence.createDataset()
}
val listener = system.actorOf(Props(new BookRestService(persistence)), name = "book-rest-service")
IO(Http) ! Http.Bind(listener, interface = "localhost", port = 9001)
}
示例5: GoogleBooksApiStub
//设置package包名称以及导入依赖的类
package org.packtpublishing.stub
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern._
import akka.util.Timeout
import scala.concurrent.Await
import scala.concurrent.duration._
import spray.can.Http
import spray.can.server.ServerSettings
import spray.routing._
import Directives._
class GoogleBooksApiStub(val route: Route) {
implicit val system = ActorSystem("google-books-api")
implicit val timeout: Timeout = 3 seconds
val settings = ServerSettings(system).copy(sslEncryption = false)
val handler = system.actorOf(Props(new GoogleBooksRestService(route)), name = "handler")
def start(port: Int) =
Await.ready(IO(Http) ? Http.Bind(handler,
interface = "localhost", port = port, settings = Some(settings)), timeout.duration)
def stop() = {
IO(Http) ? Http.CloseAll
system.stop(handler)
}
}
sealed class GoogleBooksRestService(val route: Route) extends HttpServiceActor {
def receive = runRoute {
route
}
}
示例6: GetAddress
//设置package包名称以及导入依赖的类
package wow.common.network
import java.net.InetSocketAddress
import akka.actor.{Actor, ActorLogging, Props, SupervisorStrategy}
import akka.io.Tcp._
import akka.io.{IO, Tcp}
case object GetAddress
class TCPServer[A <: TCPSessionFactory](val factory: A, val address: String, val port: Int)
extends Actor with ActorLogging {
log.debug("Binding server with socket")
IO(Tcp)(context.system) ! Bind(self, new InetSocketAddress(address, port))
override def supervisorStrategy: SupervisorStrategy = SupervisorStrategy.stoppingStrategy
override def postStop(): Unit = log.debug(s"Stopped TCP server for $address:$port")
def receive: PartialFunction[Any, Unit] = {
case Bound(localAddress) =>
log.debug(s"TCP port opened at: ${localAddress.getHostString}:${localAddress.getPort}")
case Connected(remote, local) =>
log.debug(s"Remote connection set from $remote to $local")
val handlerRef = context.actorOf(factory.props(sender), factory.PreferredName + TCPSession.PreferredName(remote))
sender ! Register(handlerRef)
case CommandFailed(_: Bind) => context stop self
}
}
object TCPServer {
def props[A <: TCPSessionFactory](companion: A, address: String, port: Int): Props = Props(classOf[TCPServer[A]],
companion,
address,
port)
val PreferredName = "tcp"
}
示例7: 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
}
}
}
示例8: MyServiceActor
//设置package包名称以及导入依赖的类
package akka_in_action.MyServer
import akka.actor.{Props, ActorSystem, Actor}
import akka.io.IO
import spray.can.Http
import spray.routing.HttpService
import spray.http.MediaTypes._
trait MyService extends HttpService {
val myRoute = {
path("something") {
respondWithMediaType(`text/plain`) {
complete("okay")
}
}
path("hello") {
respondWithMediaType(`text/plain`) {
complete("kitty")
}
}
}
}
class MyServiceActor extends Actor with MyService {
def actorRefFactory = context
def receive = runRoute(myRoute)
}
object server extends App {
try {
implicit val system = ActorSystem("my-system")
val handler = system.actorOf(Props[MyServiceActor], name = "my-service")
IO(Http) ! Http.Bind(handler, interface = "localhost", port = 8080)
} catch {
case e: Throwable => println("error: ", e)
}
}
示例9: MCWhitelistServer
//设置package包名称以及导入依赖的类
package com.amadornes.modcast.bot.servers
import java.net.InetSocketAddress
import akka.actor.{Actor, ActorRef}
import akka.io.{IO, Tcp}
import akka.util.ByteString
import com.amadornes.modcast.bot.Configuration
import grizzled.slf4j.Logging
import scala.collection.mutable.ArrayBuffer
class MCWhitelistServer extends Actor with Logging {
import Tcp._
import context.system
IO(Tcp) ! Bind(self, new InetSocketAddress(Configuration.config.getString("mc.host"), Configuration.config.getInt("mc.port")))
val connections = new ArrayBuffer[ActorRef]()
def receive = {
case str: String =>
//Ignored
case [email protected](localAddress) =>
info("MC Whitelist TCP Server is online and listening.")
case CommandFailed(_: Bind) =>
error("Bind failed. MC Whitelist Server is not functional.")
context stop self
case [email protected](remote, local) =>
if (Configuration.config.getStringList("mc.acceptedIPs").contains(remote.getAddress.getHostAddress)) {
sender() ! Register(self)
connections += sender()
} else {
warn(s"Refusing connection from ${remote.getAddress.getHostAddress}")
sender() ! Close
}
case MCWhitelistServer.WhitelistUser(userID) =>
for (connection <- connections)
connection ! Write(ByteString(s"W$userID\n"))
case MCWhitelistServer.UnWhitelistUser(userID) =>
for (connection <- connections)
connection ! Write(ByteString(s"U$userID\n"))
}
}
object MCWhitelistServer {
case class WhitelistUser(id: String)
case class UnWhitelistUser(id: String)
}
示例10: ServerApp
//设置package包名称以及导入依赖的类
package com.sretsnom.mangareader.server
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import com.sretsnom.mangareader.server.ServiceConfig.HttpConfig._
import com.typesafe.scalalogging.LazyLogging
import spray.can.Http
object ServerApp extends App with LazyLogging {
implicit val system = ActorSystem("mr-server")
val httpServer = system.actorOf(Props[HttpServerActor], "httpserver")
logger.info(banner)
IO(Http) ! Http.Bind(httpServer, interface, port)
private def banner =
"""
=============================================================
`-:- .:-.
`-+shmNNNo :NNNmdy+:`
-hmNNNNNNNNo :NNNNNNNNNd/
`hNNNNNNNNNo :NNNNNNNNNm.
`omNNNNNNNs /NNNNNNNNy.
`+hNNNNNN+:/+oo+////+ooo+//mNNNNNdo.
.sNNNNNNmo. `/dNNNNNNh:
`+hNNNNNN+:/+oo+////+ooo+//mNNNNNdo.
`omNNNNNNNs /NNNNNNNNy.
`hNNNNNNNNNo :NNNNNNNNNm.
-hmNNNNNNNNo :NNNNNNNNNd/
`-+sdmNNNo :NNNmdy+:`
`-:- .:-.
=============================================================
IDM SELF SERVICE TOOLING
""".stripMargin
}
示例11: sending
//设置package包名称以及导入依赖的类
package eu.shiftforward.apso.spray
import akka.actor.ActorSystem
import akka.io.IO
import spray.can.Http
import spray.http.{ HttpHeader, HttpRequest, RemoteAddress, Uri }
import spray.http.HttpHeaders.{ `Remote-Address`, `X-Forwarded-For` }
import spray.routing.{ Directive1, RequestContext, Route }
trait ProxySupport extends ClientIPDirectives {
private def sending(f: RequestContext => HttpRequest)(implicit system: ActorSystem): Route = {
val transport = IO(Http)(system)
ctx => transport.tell(f(ctx), ctx.responder)
}
private def getHeaders(ip: Option[RemoteAddress], headers: List[HttpHeader] = Nil) = {
// filter `Host` header
val hs = headers.filterNot(header => header.is("host"))
// add `X-Forwarded-For` header
ip.fold(hs)(addForwardedFor(_, hs))
}
private def addForwardedFor(ip: RemoteAddress, headers: List[HttpHeader]): List[HttpHeader] = {
headers match {
case Nil =>
// No `X-Forwarded-For` found in headers, so just add the new one
`X-Forwarded-For`(ip) :: Nil
case `X-Forwarded-For`(ips) :: tail =>
`X-Forwarded-For`(ips :+ ip) :: tail
case notForwardedFor :: tail =>
notForwardedFor :: addForwardedFor(ip, tail)
}
}
private val optionalRemoteAddress: Directive1[Option[RemoteAddress]] =
headerValuePF { case `Remote-Address`(address) => Some(address) } | provide(None)
def proxyTo(uri: Uri)(implicit system: ActorSystem): Route = {
optionalRemoteAddress { ip =>
sending(ctx => ctx.request.copy(
uri = uri,
headers = getHeaders(ip, ctx.request.headers)))
}
}
def proxyToUnmatchedPath(uri: Uri)(implicit system: ActorSystem): Route = {
optionalRemoteAddress { ip =>
sending { ctx =>
ctx.request.copy(
uri = uri.withPath(uri.path.++(ctx.unmatchedPath)).withQuery(ctx.request.uri.query),
headers = getHeaders(ip, ctx.request.headers))
}
}
}
}
示例12: TcpClient
//设置package包名称以及导入依赖的类
package controllers
import java.net.InetSocketAddress
import akka.actor.Actor
import akka.io.{IO, Tcp}
import akka.util.ByteString
import scala.concurrent.Promise
import Tcp._
class TcpClient(remote: InetSocketAddress, requestData: String, thePromise: Promise[String]) extends Actor {
import context.system
println("Connecting")
IO(Tcp) ! Connect(remote)
def receive = {
case CommandFailed(_: Connect) =>
println ("Connect failed")
context stop self
case c @ Connected(remote, local) =>
println ("Connect succeeded")
val connection = sender()
connection ! Register(self)
println("Sending request early")
connection ! Write(ByteString(requestData))
context become {
case CommandFailed(w: Write) =>
println("Failed to write request.")
case Received(data) =>
println("Received response.")
thePromise.success(data.decodeString("UTF-8"))
case "close" =>
println("Closing connection")
connection ! Close
case _: ConnectionClosed =>
println("Connection closed by server.")
context stop self
}
case _ => println("Something else is up.")
}
}
示例13: TwitterApi
//设置package包名称以及导入依赖的类
package core
import akka.actor.{Actor, Props, ActorSystem}
import spray.can.Http
import spray.http._
import spray.http.HttpRequest
import spray.http.HttpResponse
import akka.io.IO
import scala.io.Source
class TwitterApi private(system: ActorSystem, port: Int, body: String) {
private class Service extends Actor {
def receive: Receive = {
case _: Http.Connected =>
sender ! Http.Register(self)
case HttpRequest(HttpMethods.POST, _, _, _, _) =>
sender ! ChunkedResponseStart(HttpResponse(StatusCodes.OK))
sender ! MessageChunk(body = body)
sender ! ChunkedMessageEnd()
}
}
private val service = system.actorOf(Props(new Service))
private val io = IO(Http)(system)
io ! Http.Bind(service, "localhost", port = port)
def stop(): Unit = {
io ! Http.Unbind
system.stop(service)
system.stop(io)
}
}
object TwitterApi {
def apply(port: Int)(implicit system: ActorSystem): TwitterApi = {
val body = Source.fromInputStream(getClass.getResourceAsStream("/tweet.json")).mkString
new TwitterApi(system, port, body)
}
}
示例14: GoogleBooksApiStub
//设置package包名称以及导入依赖的类
package org.packtpublishing.stub
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern._
import akka.util.Timeout
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.language.postfixOps
import spray.can.Http
import spray.can.server.ServerSettings
import spray.routing._
import Directives._
class GoogleBooksApiStub(val route: Route) {
implicit val system = ActorSystem("google-books-api")
implicit val timeout: Timeout = 3 seconds
val settings = ServerSettings(system).copy(sslEncryption = false)
val handler = system.actorOf(Props(new GoogleBooksRestService(route)), name = "handler")
def start(port: Int) =
Await.ready(IO(Http) ? Http.Bind(handler,
interface = "localhost", port = port, settings = Some(settings)), timeout.duration)
def stop() = {
IO(Http) ? Http.CloseAll
system.stop(handler)
}
}
sealed class GoogleBooksRestService(val route: Route) extends HttpServiceActor {
def receive = runRoute {
route
}
}
示例15: LoginServer
//设置package包名称以及导入依赖的类
package com.vinctus.venatus.servers
import akka.actor.{ Actor, Props }
import akka.io.{ IO, Tcp }
import java.net.InetSocketAddress
import com.vinctus.venatus.handlers.LoginHandler
class LoginServer extends Actor {
import Tcp._
import context.system
IO(Tcp) ! Tcp.Bind(self, new InetSocketAddress("localhost", 6666))
def receive = {
case Tcp.CommandFailed(_: Bind) =>
context.stop(self)
case c @ Tcp.Connected(remote, local) =>
val handler = context.actorOf(Props[LoginHandler])
val connection = sender
connection ! Tcp.Register(handler)
}
}