本文整理汇总了Scala中java.net.SocketAddress类的典型用法代码示例。如果您正苦于以下问题:Scala SocketAddress类的具体用法?Scala SocketAddress怎么用?Scala SocketAddress使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SocketAddress类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: SocketUtil
//设置package包名称以及导入依赖的类
package akka.testkit
import scala.collection.immutable
import java.net.InetSocketAddress
import java.net.SocketAddress
import java.nio.channels.DatagramChannel
import java.nio.channels.ServerSocketChannel
object SocketUtil {
import scala.language.reflectiveCalls
// Structural type needed since DatagramSocket and ServerSocket has no common ancestor apart from Object
private type GeneralSocket = {
def bind(sa: SocketAddress): Unit
def close(): Unit
def getLocalPort(): Int
}
def temporaryServerAddress(address: String = "127.0.0.1", udp: Boolean = false): InetSocketAddress =
temporaryServerAddresses(1, address, udp).head
def temporaryServerAddresses(numberOfAddresses: Int, hostname: String = "127.0.0.1", udp: Boolean = false): immutable.IndexedSeq[InetSocketAddress] = {
Vector.fill(numberOfAddresses) {
val serverSocket: GeneralSocket =
if (udp) DatagramChannel.open().socket()
else ServerSocketChannel.open().socket()
serverSocket.bind(new InetSocketAddress(hostname, 0))
(serverSocket, new InetSocketAddress(hostname, serverSocket.getLocalPort))
} collect { case (socket, address) ? socket.close(); address }
}
}
示例2: 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))
}
示例3: NioSocketChannel
//设置package包名称以及导入依赖的类
package knot.remote.channel
import java.net.SocketAddress
import java.nio.ByteBuffer
import java.nio.channels.SocketChannel
object NioSocketChannel {
def apply(): NioSocketChannel = new NioSocketChannel(SocketChannel.open())
}
class NioSocketChannel(override val channel: SocketChannel) extends NioChannel(channel) {
lazy val incomingBuffer: ByteBuffer = ByteBuffer.allocate(1)
lazy val outgoingBuffer: ByteBuffer = ByteBuffer.allocate(1)
def connect(socketAddress: SocketAddress): Boolean = channel.connect(socketAddress)
def finishConnect: Boolean = channel.finishConnect()
override def bind(address: SocketAddress): Unit = channel.bind(address)
override def readInternal(): Int = {
val r = channel.read(incomingBuffer)
incomingBuffer.flip()
r
}
override def writeInternal(bytes: Array[Byte]): Unit = {
outgoingBuffer.put(bytes)
}
override def flushInternal(): Unit = {
if (!isFlushPending) {
setOpWrite()
outgoingBuffer.flip()
val r = channel.write(outgoingBuffer)
log.debug(s"CLIENT: Write. $r")
if (!outgoingBuffer.hasRemaining) {
outgoingBuffer.clear()
clearOpWrite()
}
}
}
}
示例4: ThriftMuxClient
//设置package包名称以及导入依赖的类
package com.example
import java.net.SocketAddress
import com.twitter.finagle._
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.param.Label
import com.twitter.finagle.thrift.ThriftClientRequest
import com.twitter.util.{Await, Future}
object ThriftMuxClient {
def main(args: Array[String]) {
val futureIface = FilteredThriftMux.newIface[Hello.FutureIface]("localhost:8081")
println(Await.result(futureIface.hi()))
}
}
object FilteredThriftMux extends Client[ThriftClientRequest, Array[Byte]]
with ThriftRichClient
with Server[Array[Byte], Array[Byte]] with ThriftRichServer {
import ThriftMux._
val filter = new SimpleFilter[ThriftClientRequest, Array[Byte]] {
override def apply(request: ThriftClientRequest, service: Service[ThriftClientRequest, Array[Byte]]): Future[Array[Byte]] = {
println("Filtered")
service(request)
}
}
override def newService(dest: Name, label: String): Service[ThriftClientRequest, Array[Byte]] = {
filter andThen ThriftMux.newService(dest, label)
}
override def newClient(dest: Name, label: String): ServiceFactory[ThriftClientRequest, Array[Byte]] = ThriftMux.newClient(dest, label)
override protected def params: Stack.Params = client.params
override protected lazy val Label(defaultClientName) = Thrift.client.params[Label]
override def serve(addr: SocketAddress, service: ServiceFactory[Array[Byte], Array[Byte]]): ListeningServer = ThriftMux.serve(addr, service)
override protected val Thrift.param.ProtocolFactory(protocolFactory) = Thrift.client.params[Thrift.param.ProtocolFactory]
}
示例5: TransportImpl
//设置package包名称以及导入依赖的类
package com.twitter.finagle.mysql.transport
import com.twitter.finagle.client.Transporter
import com.twitter.finagle.framer.LengthFieldFramer
import com.twitter.finagle.mysql.Toggles
import com.twitter.finagle.netty3.Netty3Transporter
import com.twitter.finagle.netty4.Netty4Transporter
import com.twitter.finagle.server.ServerInfo
import com.twitter.finagle.Stack
import com.twitter.finagle.toggle.Toggle
import com.twitter.finagle.transport.Transport
import com.twitter.util.Future
import java.net.SocketAddress
object TransportImpl {
private val UseNetty4ToggleId: String = "com.twitter.finagle.mysql.UseNetty4"
private val netty4Toggle: Toggle[Int] = Toggles(UseNetty4ToggleId)
private def useNetty4: Boolean = netty4Toggle(ServerInfo().id.hashCode)
val Netty3: TransportImpl = TransportImpl(params => Netty3Transporter(MysqlClientPipelineFactory, params))
val Netty4: TransportImpl = TransportImpl { params =>
new Transporter[Packet, Packet] {
private[this] val bufTransporter = Netty4Transporter(Some(framerFactory), params)
def apply(addr: SocketAddress): Future[Transport[Packet, Packet]] = {
bufTransporter(addr).map { bufTransport =>
bufTransport.map(_.toBuf, Packet.fromBuf)
}
}
// Used in the registry
override def toString = bufTransporter.toString
}
}
implicit val param: Stack.Param[TransportImpl] = Stack.Param(
if (useNetty4) Netty4
else Netty3
)
private val framerFactory = () => {
new LengthFieldFramer(
lengthFieldBegin = 0,
lengthFieldLength = 3,
lengthAdjust = Packet.HeaderSize, // Packet size field doesn't include the header size.
maxFrameLength = Packet.HeaderSize + Packet.MaxBodySize,
bigEndian = false
)
}
}
case class TransportImpl(transporter: Stack.Params => Transporter[Packet, Packet]) {
def mk(): (TransportImpl, Stack.Param[TransportImpl]) = {
(this, TransportImpl.param)
}
}
示例6: Available
//设置package包名称以及导入依赖的类
package com.twitter.finagle.context
import com.twitter.finagle.thrift.ClientId
import com.twitter.finagle.tracing.TraceId
import java.net.SocketAddress
case class Available(
upstreamAddr: Option[SocketAddress],
upstreamId: Option[ClientId],
downstreamAddr: Option[SocketAddress],
downstreamId: Option[ClientId],
traceId: TraceId)
extends RemoteInfo
{
private[this] val upstreamAddrStr = upstreamAddr match {
case Some(addr) => addr.toString
case None => "Not Available"
}
private[this] val upstreamIdStr = upstreamId match {
case Some(clientId) => clientId.name
case None => "Not Available"
}
private[this] val downstreamAddrStr = downstreamAddr match {
case Some(addr) => addr.toString
case None => "Not Available"
}
private[this] val downstreamIdStr = downstreamId match {
case Some(clientId) => clientId.name
case None => "Not Available"
}
override def toString(): String =
s"Upstream Address: $upstreamAddrStr, Upstream Client Id: $upstreamIdStr, " +
s"Downstream Address: $downstreamAddrStr, Downstream Client Id: $downstreamIdStr, " +
s"Trace Id: $traceId"
}
}
示例7: ServerRegistry
//设置package包名称以及导入依赖的类
package com.twitter.finagle.server
import com.twitter.finagle.util.{InetSocketAddressUtil, StackRegistry}
import com.twitter.logging.Level
import java.net.SocketAddress
import java.util.logging.Logger
private[twitter] object ServerRegistry extends StackRegistry {
private val log = Logger.getLogger(getClass.getName)
private var addrNames = Map[SocketAddress, String]()
def registryName: String = "server"
// This is a terrible hack until we have a better
// way of labeling addresses.
def register(addr: String): SocketAddress = synchronized {
addr.split("=", 2) match {
case Array(addr) =>
val Seq(ia) = InetSocketAddressUtil.parseHosts(addr)
ia
case Array(name, addr) =>
log.log(Level.WARNING, "Labeling servers with the <label>=<addr>" +
" syntax is deprecated! Configure your server with a" +
" com.twitter.finagle.param.Label instead.")
val Seq(ia) = InetSocketAddressUtil.parseHosts(addr)
addrNames += (ia -> name)
ia
}
}
def nameOf(addr: SocketAddress): Option[String] = synchronized {
addrNames.get(addr)
}
}
示例8: socksProxyHost
//设置package包名称以及导入依赖的类
package com.twitter.finagle
package socks
import com.twitter.app.GlobalFlag
import java.net.{SocketAddress, InetSocketAddress}
private[finagle] object socksProxyHost extends GlobalFlag("", "SOCKS proxy host") { override val name = "socksProxyHost" }
private[finagle] object socksProxyPort extends GlobalFlag(0, "SOCKS proxy port") { override val name = "socksProxyPort" }
private[finagle] object socksUsernameFlag extends GlobalFlag("", "SOCKS username") { override val name = "socksUsername" }
private[finagle] object socksPasswordFlag extends GlobalFlag("", "SOCKS password") { override val name = "socksPassword" }
private[finagle] object SocksProxyFlags {
def socksProxy: Option[SocketAddress] =
(socksProxyHost.get, socksProxyPort.get) match {
case (Some(host), Some(port)) => Some(new InetSocketAddress(host, port))
case _ => None
}
def socksUsernameAndPassword: Option[(String, String)] =
(socksUsernameFlag.get, socksPasswordFlag.get) match {
case (Some(username), Some(password)) => Some((username,password))
case _ => None
}
}
示例9: ExceptionRemoteInfoFactory
//设置package包名称以及导入依赖的类
package com.twitter.finagle.service
import java.net.SocketAddress
import com.twitter.finagle._
import com.twitter.finagle.client.Transporter
import com.twitter.finagle.context.RemoteInfo
import com.twitter.finagle.context.RemoteInfo.Upstream
import com.twitter.finagle.thrift.ClientId
import com.twitter.finagle.tracing.Trace
import com.twitter.util.Future
private[finagle] object ExceptionRemoteInfoFactory {
val role = Stack.Role("ExceptionRemoteInfo")
def addRemoteInfo[T](endpointAddr: SocketAddress, label: String): PartialFunction[Throwable, Future[T]] = {
case e: HasRemoteInfo =>
e.setRemoteInfo(RemoteInfo.Available(
Upstream.addr, ClientId.current, Some(endpointAddr), Some(ClientId(label)), Trace.id))
Future.exception(e)
case f: Failure =>
Future.exception(f.withSource(Failure.Source.RemoteInfo, RemoteInfo.Available(
Upstream.addr, ClientId.current, Some(endpointAddr), Some(ClientId(label)), Trace.id)))
}
private[finagle] class ExceptionRemoteInfoFactory[Req, Rep](
underlying: ServiceFactory[Req, Rep],
endpointAddr: SocketAddress,
label: String)
extends ServiceFactoryProxy[Req, Rep](underlying)
{
private[this] val requestAddRemoteInfo: PartialFunction[Throwable, Future[Rep]] =
ExceptionRemoteInfoFactory.addRemoteInfo(endpointAddr, label)
private[this] val connectionAddRemoteInfo: PartialFunction[Throwable, Future[Service[Req,Rep]]] =
ExceptionRemoteInfoFactory.addRemoteInfo(endpointAddr, label)
override def apply(conn: ClientConnection): Future[Service[Req, Rep]] =
underlying(conn).map { service =>
val filter = new SimpleFilter[Req, Rep] {
override def apply(request: Req, service: Service[Req, Rep]): Future[Rep] =
service(request).rescue(requestAddRemoteInfo)
}
filter andThen service
}.rescue(connectionAddRemoteInfo)
}
示例10: NameTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle
import com.twitter.util.{Witness, Var}
import java.net.{InetSocketAddress, SocketAddress}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class NameTest extends FunSuite {
test("Name.fromGroup") {
val g = Group.mutable[SocketAddress]()
val n = Name.fromGroup(g)
var addr: Addr = Addr.Pending
n.addr.changes.register(Witness({ addr = _ }))
assert(addr == Addr.Pending)
val set = Set[SocketAddress](new InetSocketAddress(0), new InetSocketAddress(1))
g() = set
val Addr.Bound(s2, r) = addr
assert(s2.collect { case Address.Inet(ia, _) => ia } == set)
assert(r.isEmpty)
g() = Set(new SocketAddress {})
val Addr.Failed(e) = addr
assert(e.isInstanceOf[IllegalArgumentException])
}
test("Name.Bound maintains equality as per 'id'") {
val id1, id2 = new {}
val a1, a2 = Var(Addr.Pending)
assert(Name.Bound(a1, id1) == Name.Bound(a2, id1))
assert(Name.Bound(a1, id1) != Name.Bound(a1, id2))
// It sucks that this is not symmetric, oh well.
assert(Name.Bound(a1, id1) == id1)
assert(Name.Bound(a1, id1) != id2)
}
test("Name.all maintains equality") {
val names = Seq.fill(10) { Name.Bound.singleton(Var(Addr.Pending)) }.toSet
assert(Name.all(names) == Name.all(names))
assert(Name.all(names) != Name.all(names drop 1))
}
}
示例11: PriorKnowledgeTransporter
//设置package包名称以及导入依赖的类
package com.twitter.finagle.http2.transport
import com.twitter.cache.FutureCache
import com.twitter.finagle.client.Transporter
import com.twitter.finagle.http2.Http2Transporter
import com.twitter.finagle.http2.transport.Http2ClientDowngrader.StreamMessage
import com.twitter.finagle.transport.Transport
import com.twitter.util.Future
import java.net.SocketAddress
import java.util.concurrent.ConcurrentHashMap
private[http2] class PriorKnowledgeTransporter(
underlying: Transporter[Any, Any])
extends Transporter[Any, Any] {
private[this] val cache = new ConcurrentHashMap[SocketAddress, Future[MultiplexedTransporter]]()
private[this] val fn: SocketAddress => Future[MultiplexedTransporter] = { addr: SocketAddress =>
underlying(addr).map { transport =>
val multi = new MultiplexedTransporter(
Transport.cast[StreamMessage, StreamMessage](transport),
addr
)
multi.onClose.ensure {
cache.remove(addr, multi)
}
multi
}
}
private[this] val cachedFn = FutureCache.fromMap(fn, cache)
def apply(addr: SocketAddress): Future[Transport[Any, Any]] =
cachedFn(addr).map { multi => Http2Transporter.unsafeCast(multi()) }
}
示例12: read
//设置package包名称以及导入依赖的类
package com.twitter.finagle.http.exp
import com.twitter.finagle.Status
import com.twitter.finagle.transport.Transport
import com.twitter.util.{Future, Time}
import java.net.SocketAddress
import java.security.cert.Certificate
def read(): Future[Multi[Out]]
}
private[finagle] abstract class StreamTransportProxy[In, Out](self: Transport[_, _])
extends StreamTransport[In, Out] {
def status: Status = self.status
val onClose: Future[Throwable] = self.onClose
def localAddress: SocketAddress = self.localAddress
def remoteAddress: SocketAddress = self.remoteAddress
def close(deadline: Time): Future[Unit] = self.close(deadline)
def peerCertificate: Option[Certificate] = self.peerCertificate
}
示例13: applyToCodec
//设置package包名称以及导入依赖的类
package com.twitter.finagle.http
import com.twitter.finagle.http.param._
import com.twitter.finagle.client.Transporter
import com.twitter.finagle.http.{Http => HttpCodec}
import com.twitter.finagle.netty3.{Netty3Listener, Netty3Transporter}
import com.twitter.finagle.param.{Label, Stats}
import com.twitter.finagle.server.Listener
import com.twitter.finagle.{ServerCodecConfig, Stack, ClientCodecConfig}
import java.net.SocketAddress
import org.jboss.netty.channel.Channel
package object netty {
private[this] def applyToCodec(params: Stack.Params, codec: HttpCodec): HttpCodec =
codec
.maxRequestSize(params[MaxRequestSize].size)
.maxResponseSize(params[MaxResponseSize].size)
.streaming(params[Streaming].enabled)
.decompressionEnabled(params[Decompression].enabled)
.compressionLevel(params[CompressionLevel].level)
.maxInitialLineLength(params[MaxInitialLineSize].size)
.maxHeaderSize(params[MaxHeaderSize].size)
private[finagle] val Netty3HttpTransporter: Stack.Params => Transporter[Any, Any] = { params =>
val Label(label) = params[Label]
val codec = applyToCodec(params, Http())
.client(ClientCodecConfig(label))
val Stats(stats) = params[Stats]
val newTransport = (ch: Channel) => codec.newClientTransport(ch, stats)
Netty3Transporter(
codec.pipelineFactory,
params + Netty3Transporter.TransportFactory(newTransport))
}
private[finagle] val Netty3HttpListener: Stack.Params => Listener[Any, Any] = { params =>
val Label(label) = params[Label]
val httpPipeline =
applyToCodec(params, HttpCodec())
.server(ServerCodecConfig(label, new SocketAddress{}))
.pipelineFactory
Netty3Listener(httpPipeline, params)
}
}
示例14: ServerTransport
//设置package包名称以及导入依赖的类
package com.twitter.finagle.memcached.protocol.text.server
import com.twitter.finagle.Status
import com.twitter.finagle.memcached.protocol.text.{ResponseToEncoding, Decoding, Encoder}
import com.twitter.finagle.memcached.protocol.{Response, Command}
import com.twitter.finagle.memcached.protocol.StorageCommand.StorageCommands
import com.twitter.finagle.transport.Transport
import com.twitter.io.Buf
import com.twitter.util.{Time, Future}
import java.net.SocketAddress
import java.security.cert.Certificate
private[finagle] class ServerTransport(
underlying: Transport[Buf, Buf]
) extends Transport[Response, Command] {
private[this] val encoder = new Encoder
private[this] val decoder = new ServerDecoder(StorageCommands)
private[this] val responseToEncoding = new ResponseToEncoding
private[this] val decodingToCommand = new DecodingToCommand
// Decoding must be in a read loop because read() must return a response,
// but we may get only get a partial message from the transport,
// necessitating a further read.
private[this] val decode: Buf => Future[Command] = buf => {
val decoding: Decoding = decoder.decode(buf)
if (decoding != null) {
Future.value(decodingToCommand.decode(null, null, decoding))
} else {
readLoop()
}
}
private[this] def readLoop(): Future[Command] = underlying.read().flatMap(decode)
def read(): Future[Command] = readLoop()
def write(response: Response): Future[Unit] = {
val decoding: Decoding = responseToEncoding.encode(null, null, response)
val buf: Buf = encoder.encode(null, null, decoding)
underlying.write(buf)
}
def remoteAddress: SocketAddress = underlying.remoteAddress
def peerCertificate: Option[Certificate] = underlying.peerCertificate
def onClose: Future[Throwable] = underlying.onClose
def localAddress: SocketAddress = underlying.localAddress
def status: Status = underlying.status
def close(deadline: Time): Future[Unit] = underlying.close(deadline)
}
示例15: ClientTransport
//设置package包名称以及导入依赖的类
package com.twitter.finagle.memcached.protocol.text.client
import com.twitter.finagle.Status
import com.twitter.finagle.memcached.protocol.text._
import com.twitter.finagle.transport.Transport
import com.twitter.io.Buf
import com.twitter.util.{Time, Future}
import java.net.SocketAddress
import java.security.cert.Certificate
private[finagle] class ClientTransport[Command <: AnyRef, Response <: AnyRef](
commandToEncoding: AbstractCommandToEncoding[Command],
decodingToResponse: AbstractDecodingToResponse[Response],
underlying: Transport[Buf, Buf])
extends Transport[Command, Response] {
private[this] val decoder = new ClientDecoder
private[this] val encoder = new Encoder
// Decoding must be in a read loop because read() must return a response,
// but we may get only get a partial message from the transport,
// necessitating a further read.
private[this] val decode: Buf => Future[Response] = buf => {
val decoding: Decoding = decoder.decode(buf)
if (decoding != null) {
Future.value(decodingToResponse.decode(decoding))
} else {
readLoop()
}
}
private[this] def readLoop(): Future[Response] = underlying.read().flatMap(decode)
def read(): Future[Response] = readLoop()
def write(command: Command): Future[Unit] = {
val decoding: Decoding = commandToEncoding.encode(command)
val buf: Buf = encoder.encode(null, null, decoding)
underlying.write(buf)
}
def remoteAddress: SocketAddress = underlying.remoteAddress
def peerCertificate: Option[Certificate] = underlying.peerCertificate
def onClose: Future[Throwable] = underlying.onClose
def localAddress: SocketAddress = underlying.localAddress
def status: Status = underlying.status
def close(deadline: Time): Future[Unit] = underlying.close(deadline)
}