• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Socket类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: WiremockStart

//设置package包名称以及导入依赖的类
package uk.co.telegraph.sbt.wiremock.tasks

import java.net.Socket

import sbt._
import sbt.Keys.TaskStreams

import scala.util.Try

object WiremockStart {

  import uk.co.telegraph.sbt.process.ProcessId._

  private def isPortAvailable(port:Int):Boolean = {
    Try( new Socket("localhost", port).close() ).isSuccess
  }

  def apply(
    targetDir:File,
    httpPort:Int,
    httpsPort:Option[Int],
    otherArgs:Map[String, Any],
    logger:Logger
  ):String = {
    val localJar = new File(targetDir, "wiremock-standalone.jar")

    //Check ports available
    if( isPortAvailable(httpPort) ){
      sys.error(s"Port already being used [$httpPort].")
    }
    if( httpsPort.exists(isPortAvailable) ){
      sys.error(s"Port already being used [$httpPort].")
    }

    val args = Seq("java") ++
      Seq("-jar", localJar.getAbsolutePath) ++
      Seq("--port", httpPort.toString) ++
      httpsPort.map( p => Seq("--https-port", p.toString)).getOrElse(Seq.empty) ++
      otherArgs.flatMap({
        case (key, Some(value)) => Seq(key, value.toString)
        case (key, true       ) => Seq(key)
        case (key, value      ) => Seq(key, value.toString)
      })

    logger.info ("Starting Wiremock")
    logger.info(s"   Application: ${localJar.getPath}")
    logger.info(s"   Arguments  : ${args.toString}")
    Process(args).run()
    do {
      logger.info (s"Waiting for Wiremock to boot on port [$httpPort]")
      Thread.sleep( 500 )
    }while(!isPortAvailable(httpPort))

    extractPid("jps -ml".!!, httpPort, localJar).getOrElse {
      sys.error(s"Cannot find wiremock PID running on $httpPort")
    }
  }
} 
开发者ID:telegraph,项目名称:sbt-wiremock,代码行数:59,代码来源:WiremockStart.scala


示例2: FqueueStreamingReceiver

//设置package包名称以及导入依赖的类
import java.io.{BufferedReader, InputStreamReader}
import java.net.Socket

import Fqueue.FqueueReceiver
import org.apache.spark.Logging
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.receiver.Receiver


class FqueueStreamingReceiver(val address: String, val connectionPoolSize: Int, val timeOut: Int)
  extends Receiver[String](StorageLevel.MEMORY_AND_DISK_2) with Logging {
  private var receiver: Option[FqueueReceiver] = None

  def onStart() {
    new Thread("Socket Receiver") {
      override def run() { receive() }
    }.start()
  }

  def onStop(): Unit = {
    receiver foreach { _.stop() }
  }

  private def receive(): Unit = {
    val fqueueReceiver = new FqueueReceiver(address, connectionPoolSize, timeOut)
    receiver = Some(fqueueReceiver)
    receiver foreach { _.connect() }

    try
    {
      var stop = false
      while (!isStopped() && !stop) {
        val data = fqueueReceiver.deQueue("track_BOdao2015*")
        data match {
          case Some(str) => store(str)
          case None => Thread.sleep(1000)//stop = true
        }
      }
      receiver foreach { _.stop() }
    } catch {
      case e: Exception =>
        println("get data from fqueue err! pleace sure the server is live")
        println(e.getMessage)
        println(e.getStackTraceString)
        receiver foreach { _.stop() }
    }
  }
} 
开发者ID:TopSpoofer,项目名称:FqueueStreamingReceiver,代码行数:49,代码来源:FqueueStreamingReceiver.scala


示例3: RequestHandler

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

import java.net.Socket

import sh.webserver.railway.Rail
import sh.webserver.railway.Result
import sh.webserver.railway.Result._
import sh.webserver.request.{Request, RequestParser}

class RequestHandler(socket: Socket) extends Runnable {
  def validateHTTPMethod : Request => Result.Value = (request: Request) => {
    request.method match {
      case "GET" => SUCCESS
      case _ => FAILURE
    }
  }
  def validatePath : Request => Result.Value = (request: Request) => {
    request.path match {
      case "fail" => FAILURE
      case _ => SUCCESS
    }
  }
  def validateParameters : Request => Result.Value = (request: Request) => {
    request.parameters("fail") match {
      case "true" => FAILURE
      case _ => SUCCESS
    }
  }
  def validateHeaders : Request => Result.Value = (request: Request) => {
    request.headers("Host") match {
      case "localhost" => SUCCESS
      case _ => FAILURE
    }
  }

  def validateEverything : Request => Result.Value =
    Rail.begin(validateHTTPMethod) andThen
      Rail.switch(validatePath) andThen
      Rail.switch(validateHeaders) andThen
      Rail.end(validateParameters)

  def validatePathAndQuery : Request => Result.Value = Rail.begin(validatePath) andThen Rail.end(validateHeaders)
  def validateMethodAndQuery : Request => Result.Value = Rail.begin(validateHTTPMethod) andThen Rail.end(validateHeaders)



  def run() : Unit= {
    val request = RequestParser.parseFullRequest(socket.getInputStream)

    validateEverything(request)

    socket.getOutputStream.write("HTTP/1.1 200 OK\nCache-Control: no-cache\n\nJunge".getBytes)
    socket.getOutputStream.write(System.currentTimeMillis.toString.getBytes)
    socket.getOutputStream.close()
  }

} 
开发者ID:stefan-hering,项目名称:scalaserver,代码行数:58,代码来源:RequestHandler.scala


示例4: T02_Test

//设置package包名称以及导入依赖的类
package streaming

import java.io._
import java.net.Socket


object T02_Test {
  def main(args: Array[String]) {
    val socket = new Socket("localhost", 9999)
    val in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
    val out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true)
    println("reading!....")
    var line = in.readLine()
    while (line != null) {
      println(line)
      line = in.readLine()
    }
  }
} 
开发者ID:IMJIU,项目名称:Spark1.6,代码行数:20,代码来源:T02_Test.scala


示例5: TCPReader

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

import java.net.Socket

import pubsub.Client
import pubsub.collection.BoundedBuffer
import pubsub.command._

class TCPReader(id: Int, socket: Socket, buffer: BoundedBuffer[Command]) {
  val client = new Client(socket, id)
  val reader = new CommandReader(socket.getInputStream(), client)

  def read(): Unit = {
    client.sayHello()
    println(s"New client: ${client.name}")
    while(client.isConnected) {

      reader.fetchCommand() match {
        case c: EndOfClient =>
          buffer.put(c)
          println(c)
          client.sayGoodbye()
          client.close()
        case _: MalformedCommand =>
          client.invalidPreviousCommand()
        case command =>
          println(command)
          buffer.put(command)
      }
    }
  } 
} 
开发者ID:vincenzobaz,项目名称:Parallelism-and-Concurrency-Assignments,代码行数:33,代码来源:TCPReader.scala


示例6: Server

//设置package包名称以及导入依赖的类
package pubsub

import java.net.ServerSocket
import java.net.Socket
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL

import java.util.concurrent.Executors
import scala.concurrent.JavaConversions._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

import pubsub.collection._
import pubsub.command._
import pubsub.network.TCPReader

object Server extends App {
  val port = 7676
  val maxWorkers = 12
  val bufferSize = 20
  val socket = new ServerSocket(port)
  try {
    val whatismyip = new URL("http://checkip.amazonaws.com")
    val in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
    val serverIP = in.readLine()
    println(s"Connect to $serverIP (or `localhost`), port $port with `telnet` to join this server")
  } catch  {
    case e: Exception =>
      println("There is a problem with your internet connection, you can only access it via localhost")
  }

  val buffer = new BoundedBuffer[Command](20)
  val commandHandlers = for{
    i <- 0 until maxWorkers
  } yield {
    Future {
      new CommandHandler(buffer).handle()
    }
  }
  val threadPool = Executors.newFixedThreadPool(maxWorkers)

  var clientId = 0
  while(true) {
    val client = socket.accept();
    val cid = clientId
    clientId += 1
    Future{
      new TCPReader(clientId, client, buffer).read()
    }(threadPool)
  }
} 
开发者ID:vincenzobaz,项目名称:Parallelism-and-Concurrency-Assignments,代码行数:53,代码来源:Server.scala


示例7: NetworkUtil

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

import java.net.{InetSocketAddress, NetworkInterface, ServerSocket, Socket}
import java.io.IOException


object NetworkUtil {
  def getLocalIpAddress: Seq[String] = {
    import scala.collection.JavaConverters._
    val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toVector

    val ipAddresses = enumeration.flatMap(p =>
      p.getInetAddresses.asScala.toSeq
    )

    val address = ipAddresses.filter { address =>
      val host = address.getHostAddress
      host.contains(".") && !address.isLoopbackAddress
    }.toList
    address.map(_.getHostAddress)
  }

  def freeLocalPort: Int = try {
    val serverSocket = new ServerSocket(0)
    val port = serverSocket.getLocalPort
    serverSocket.close()
    port
  } catch {
    case e: IOException =>
      throw new IllegalStateException(e)
  }

  def checkPortReachable(ip: String, port: Int, timeoutInMilliSec: Int = 500): Boolean = {
    val s = new Socket()
    try {
      s.setReuseAddress(true)
      val sa = new InetSocketAddress(ip, port)
      s.connect(sa, timeoutInMilliSec)
      s.isConnected
    } catch {
      case e: IOException => false
    } finally {
      if (s.isConnected) s.close()
    }
  }
} 
开发者ID:cuzfrog,项目名称:eft,代码行数:47,代码来源:NetworkUtil.scala


示例8: CatClient

//设置package包名称以及导入依赖的类
package ru.ifmo.ctddev.semenov.dkvs.client

import java.io._
import java.net.Socket
import java.nio.charset.StandardCharsets.UTF_8
import java.util.concurrent.LinkedBlockingQueue

import scala.annotation.tailrec
import scala.util.{Failure, Success, Try}


class CatClient(socket: Socket) {
  val consoleReader = new BufferedReader(new InputStreamReader(System.in, UTF_8))
  val consoleWriter = new PrintWriter(new OutputStreamWriter(System.out, UTF_8))
  val socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream, UTF_8))
  val socketWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream, UTF_8), true)

  val requests  = new LinkedBlockingQueue[String]()
  val responses = new LinkedBlockingQueue[String]()

  def start(): Unit = {
    def start(action: () => Unit) = {
      new Thread(new Runnable() {
        override def run() = action()
      }).start()
    }

    start(readRequest)
    start(writeRequest)
    start(readResponse)
    start(writeResponse)
  }

  private def readRequest() = interact(consoleReader.readLine, requests add _, "exit reading requests")
  private def writeRequest() = interact(requests.take, socketWriter.println, "exit writing requests")
  private def readResponse() = interact(socketReader.readLine, responses add _, "exit reading responses")
  private def writeResponse() = interact(responses.take, consoleWriter.println, "exit writing responses")

  @tailrec private def interact(read: () => String, write: String => Unit, exitMessage: String): Unit = {
    val line = read()
    if (line == null) {
      consoleWriter println exitMessage
      return
    }
    write(line)
    interact(read, write, exitMessage)
  }
}

object Connect {
  def main(args: Array[String]) {
    if (args.length != 2) println("Usage: Client <host> <port>")
    else Try(new Socket(args(0), args(1).toInt)) match {
      case Success(socket)    => new CatClient(socket).start()
      case Failure(exception) =>
        println(s"Cannot connect to ${args(0)}:${args(1)}")
        exception.printStackTrace()
    }
  }
} 
开发者ID:vadimsemenov,项目名称:distributed-key-value-storage,代码行数:61,代码来源:CatClient.scala


示例9: IgnorantTrustManagerTest

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

import java.net.Socket
import java.security.cert.X509Certificate
import javax.net.ssl.SSLEngine
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class IgnorantTrustManagerTest extends FunSuite with MockitoSugar {

  val authType = "DHE_DSS"
  val socket = mock[Socket]
  val engine = mock[SSLEngine]
  val cert = mock[X509Certificate]
  val chain = Array(cert)

  test("an IgnorantTrustManager can be created") {
    val tm = new IgnorantTrustManager()
    assert(tm != null)
  }

  test("an IgnorantTrustManager has no accepted issuers") {
    val tm = new IgnorantTrustManager()
    val issuers = tm.getAcceptedIssuers()
    assert(issuers.length == 0)
  }

  test("checkClientTrusted does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkClientTrusted(chain, authType)
  }

  test("checkClientTrusted with socket does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkClientTrusted(chain, authType, socket)
  }

  test("checkClientTrusted with engine does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkClientTrusted(chain, authType, engine)
  }

  test("checkServerTrusted does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkServerTrusted(chain, authType)
  }

  test("checkServerTrusted with socket does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkServerTrusted(chain, authType, socket)
  }

  test("checkServerTrusted with engine does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkServerTrusted(chain, authType, engine)
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:62,代码来源:IgnorantTrustManagerTest.scala


示例10: MemcachedProxy

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

import com.twitter.finagle.memcached.protocol.text.Memcached
import com.twitter.finagle.memcached.protocol.{Command, Response}
import com.twitter.finagle.Service
import com.twitter.finagle.builder.{Server, ClientBuilder, ServerBuilder}
import java.net.{ConnectException, Socket, InetSocketAddress}


object MemcachedProxy {
  def main(args: Array[String]) {
    assertMemcachedRunning()

    val client: Service[Command, Response] = ClientBuilder()
      .codec(Memcached())
      .hosts(new InetSocketAddress(11211))
      .hostConnectionLimit(1)
      .build()

    val proxyService = new Service[Command, Response] {
      def apply(request: Command) = client(request)
    }

    val server: Server = ServerBuilder()
      .codec(Memcached())
      .bindTo(new InetSocketAddress(8080))
      .name("memcachedproxy")
      .build(proxyService)
  }

  private[this] def assertMemcachedRunning() {
    try {
      new Socket("localhost", 11211)
    } catch {
      case e: ConnectException =>
        println("Error: memcached must be running on port 11211")
        System.exit(1)
    }

  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:42,代码来源:MemcachedProxy.scala


示例11: Client

//设置package包名称以及导入依赖的类
package tcp_server

import java.net.{InetAddress, Socket }
import java.io._

import scala.io._

import runtime.Controller

object Client {
    def main(args : Array[String]) : Unit = {
        try {
            val s = new Socket(InetAddress.getByName(Controller.domain),9999)
            val in = new DataInputStream(s.getInputStream())
            val out = new ObjectOutputStream(
                new DataOutputStream(s.getOutputStream()))


            out.writeObject("Hello Server")
            out.flush()

            while (true) {
                val x = in.readChar()
                println("Received: " + x)
            }

            out.close()
            in.close()
            s.close()
        }
        catch {
            case e: IOException =>
                e.printStackTrace()
        }
    }
}

// vim: set ts=4 sw=4 et: 
开发者ID:bunny-defense,项目名称:bunny_defense,代码行数:39,代码来源:client.scala


示例12: SocketManager

//设置package包名称以及导入依赖的类
package robot

import java.io.PrintWriter
import java.net.Socket
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io._
import java.net.InetSocketAddress


class SocketManager {
  
  def sendMessage[T](toAddr: InetSocketAddress, i: T) {
    var clientSocket = new Socket();
    try {
      clientSocket.connect(toAddr);
      var pw = new PrintWriter(clientSocket.getOutputStream());
      pw.print(i);
      pw.flush();
      pw.close();
      clientSocket.close();
    } catch {
      case e: Throwable => {
        println(s"$e: Error while send message to server with ip = ${toAddr.getAddress} and port = ${toAddr.getPort}.")
      }
    } finally {
      clientSocket.close();
    }
  }

  
  def receiveMessage(toAddr: InetSocketAddress): String = {
    var clientSocket = new Socket();
    var result = ""
    try {
      clientSocket.connect(toAddr);
      var br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))
      var str = br.readLine()
      while (str != null) {
        result += str
        str = br.readLine()
      }
      br.close();
      clientSocket.close();
    } catch {
      case e: Throwable => {
        println(s"$e: Error while receive message to server with ip = ${toAddr.getAddress} and port = ${toAddr.getPort}.")
      }
    } finally {
      clientSocket.close();
    }
    return result
  }
  
} 
开发者ID:LoickBriot,项目名称:Projet3A,代码行数:56,代码来源:SocketManager.scala


示例13: SocketClient

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

import java.io.{OutputStreamWriter, PrintWriter}
import java.net.{InetSocketAddress, Socket}

class SocketClient(val serverAddress: InetSocketAddress, msgCount: Int) {
  val serverSocket = {
    val socket = new Socket()
    socket.setSoTimeout(1000)
    socket.connect(serverAddress)
    socket
  }

  def sendAndForgetBlocking(msg: String) = {
    val (elapsed, _) = measure {
      1 to msgCount foreach { i =>
        writeBlockingMsg(s"$i$msg")
      }
    }
    elapsed
  }

  def close() = serverSocket.close()

  private def writeBlockingMsg(msg: String): Unit = {
    val out = new PrintWriter(new OutputStreamWriter(serverSocket.getOutputStream, "utf-8"), true)
    out.println(msg)
    out.flush()
  }

  private def measure[T](callback: ? T): (Long, T) = {
    val start = System.currentTimeMillis
    val res = callback
    val elapsed = System.currentTimeMillis - start
    (elapsed, res)
  }

} 
开发者ID:focusj,项目名称:address-service,代码行数:39,代码来源:SocketClient.scala


示例14: TransactionGenerator

//设置package包名称以及导入依赖的类
package com.bwsw.sj.transaction.generator.server

import java.io.{DataInputStream, DataOutputStream}
import java.net.Socket
import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger, AtomicLong}

import com.bwsw.sj.common.utils.TransactionGeneratorLiterals

class TransactionGenerator(socket: Socket, doesServerWork: AtomicBoolean) extends Runnable {
  private val counter = new AtomicInteger(0)
  private val currentMillis = new AtomicLong(0)
  private val inputStream = new DataInputStream(socket.getInputStream)
  private val outputStream = new DataOutputStream(socket.getOutputStream)
  private val scale = TransactionGeneratorLiterals.scale

  override def run(): Unit = {
    try {
      while (doesServerWork.get()) {
        if (isClientAvailable) {
          val id = generateID()
          send(id)
        } else {
          close()
          return
        }
      }
    } catch {
      case ex: Exception =>
        close()
    }
  }

  private def isClientAvailable = {
    val clientRequestStatus = inputStream.read()

    clientRequestStatus != -1
  }

  private def generateID() = this.synchronized {
    val now = System.currentTimeMillis()
    if (now - currentMillis.get > 0) {
      currentMillis.set(now)
      counter.set(0)
    }
    now * scale + counter.getAndIncrement()
  }

  private def send(id: Long) {
    outputStream.writeLong(id)
  }

  private def close() = {
    inputStream.close()
    outputStream.close()
    socket.close()
  }
} 
开发者ID:bwsw,项目名称:sj-platform,代码行数:58,代码来源:TransactionGenerator.scala


示例15: Util

//设置package包名称以及导入依赖的类
package org.pgscala.embedded

import java.net.{ConnectException, Socket}
import java.security.MessageDigest
import java.util.Locale
import javax.xml.bind.DatatypeConverter

import com.typesafe.scalalogging.StrictLogging

object Util extends StrictLogging {
  def bin2Hex(binary: Array[Byte]): String =
    DatatypeConverter.printHexBinary(binary).toLowerCase(Locale.ROOT)

  def digest(text: String): Array[Byte] = {
    val md = MessageDigest.getInstance("SHA-256")
    md.digest(text.getBytes("UTF-8"))
  }

  lazy val isWindows: Boolean = OS.Name.resolved match {
    case Some(OS.Name.Windows) => true
    case _ => false
  }

  lazy val isUnix: Boolean = OS.Name.resolved match {
    case Some(OS.Name.Linux) | Some(OS.Name.OSX) => true
    case _ => false
  }

  private[this] def socketIsFree(host: String, port: Int): Boolean =
    try {
      logger.trace(s"Checking if port $port is free...")
      new Socket(host, port).close()
      logger.debug(s"Port $port is free, choosing it for the cluster")
      false
    } catch {
      case _: ConnectException =>
        true
    }

  def findFreePort(host: String, portRange: Range): Int =
    portRange.find(port => socketIsFree(host, port))
      .getOrElse(sys.error(s"Could not find free port in range: [${portRange.head},${portRange.last}]"))
} 
开发者ID:oradian,项目名称:pgscala-embedded,代码行数:44,代码来源:Util.scala


示例16: CustomSSLSocketFactory

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

import java.net.{InetAddress, Socket, URI}
import java.util
import javax.net.ssl._

object CustomSSLSocketFactory {
  def forUri(uri: URI) = forHost(uri.getHost)

  def forHost(host: String): CustomSSLSocketFactory = {
    val sniHost = new SNIHostName(host)
    val matcher = SNIHostName.createSNIMatcher(host.replace(".", "\\."))
    withSNI(matcher, sniHost)
  }

  def withSNI(sniMatcher: SNIMatcher, sniHost: SNIHostName): CustomSSLSocketFactory = {
    val sslParameters = new SSLParameters()

    sslParameters.setSNIMatchers(util.Arrays.asList(sniMatcher))
    sslParameters.setServerNames(util.Arrays.asList(sniHost))
    val ctx = SSLContext.getDefault
    val inner = ctx.getSocketFactory
    new CustomSSLSocketFactory(inner, sslParameters)
  }
}


class CustomSSLSocketFactory(inner: SSLSocketFactory, sslParameters: SSLParameters) extends SSLSocketFactory {
  override def getDefaultCipherSuites: Array[String] = inner.getDefaultCipherSuites

  override def getSupportedCipherSuites: Array[String] = inner.getSupportedCipherSuites

  override def createSocket(): Socket =
    customized(inner.createSocket())

  override def createSocket(socket: Socket, s: String, i: Int, b: Boolean): Socket =
    customized(inner.createSocket(socket, s, i, b))

  override def createSocket(s: String, i: Int): Socket =
    customized(inner.createSocket(s, i))

  override def createSocket(s: String, i: Int, inetAddress: InetAddress, i1: Int): Socket =
    customized(inner.createSocket(s, i, inetAddress, i1))

  override def createSocket(inetAddress: InetAddress, i: Int): Socket =
    customized(inner.createSocket(inetAddress, i))

  override def createSocket(inetAddress: InetAddress, i: Int, inetAddress1: InetAddress, i1: Int): Socket =
    customized(inner.createSocket(inetAddress, i, inetAddress1, i1))

  private def customized(s: Socket): Socket = {
    val sslSocket = s.asInstanceOf[SSLSocket]
    sslSocket.setSSLParameters(sslParameters)
    sslSocket
  }
} 
开发者ID:malliina,项目名称:logstreams,代码行数:57,代码来源:CustomSSLSocketFactory.scala


示例17: ConnectionServer

//设置package包名称以及导入依赖的类
package messaging

import annotation.tailrec

import java.io.InputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.OutputStream

import java.net.ServerSocket
import java.net.Socket


object ConnectionServer extends App
{
  @tailrec
  final def handleConnection (server_socket : ServerSocket,
                              connection_stream_pair_list : List[((String, Int), ObjectOutputStream)]) : Unit =
  {
    val socket : Socket = server_socket.accept
    val input_stream : InputStream = socket.getInputStream
    val output_stream : OutputStream = socket.getOutputStream
    val object_input_stream : ObjectInputStream = new ObjectInputStream (input_stream)
    val object_output_stream : ObjectOutputStream = new ObjectOutputStream (output_stream)
    val received_object : Object = object_input_stream.readObject
    val received_connection_message : Connection = received_object.asInstanceOf[Connection]
    val received_connection : (String, Int) = received_connection_message.connection
    val connection_stream_pair : ((String, Int), ObjectOutputStream) = (received_connection, object_output_stream)
    connection_stream_pair_list.foreach
    {
      connection_stream_pair : ((String, Int), ObjectOutputStream) =>
      {
        val (_, object_output_stream : ObjectOutputStream) = connection_stream_pair
        object_output_stream.writeObject (received_connection_message)
      }
    }
    val connection_list : List[(String, Int)] = connection_stream_pair_list.map
    {
      connection_stream_pair : ((String, Int), ObjectOutputStream) =>
      {
        val (connection : (String, Int), _) = connection_stream_pair
        connection
      }
    }
    val connection_list_message : ConnectionList = ConnectionList (connection_list)
    object_output_stream.writeObject (connection_list_message)
    handleConnection (server_socket, connection_stream_pair :: connection_stream_pair_list)
  }

  val local_port : Int = args(0).toInt
  val server_socket : ServerSocket = new ServerSocket (local_port)
  val connection_stream_pair_list : List[((String, Int), ObjectOutputStream)] = Nil
  handleConnection (server_socket, connection_stream_pair_list)
} 
开发者ID:vdorbs,项目名称:Control-OS,代码行数:55,代码来源:Servers.scala


示例18: RandomSocket

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

import java.io.IOException
import java.net.{InetSocketAddress, Socket}


object RandomSocket {
  private[this] def localSocketOnPort(port: Int) =
    new InetSocketAddress(port)
  private[this] val ephemeralSocketAddress = localSocketOnPort(0)

  @deprecated("RandomSocket cannot ensure that the address is not in use.", "2014-11-13")
  def apply() = nextAddress()

  @deprecated("RandomSocket cannot ensure that the address is not in use.", "2014-11-13")
  def nextAddress(): InetSocketAddress =
    localSocketOnPort(nextPort())

  @deprecated("RandomSocket cannot ensure that the address is not in use.", "2014-11-13")
  def nextPort(): Int = {
    val s = new Socket
    s.setReuseAddress(true)
    try {
      s.bind(ephemeralSocketAddress)
      s.getLocalPort
    } catch {
      case NonFatal(e) =>
        if (e.getClass == classOf[IOException] || e.getClass == classOf[IllegalArgumentException])
          throw new Exception("Couldn't find an open port: %s".format(e.getMessage))
        else
          throw e
    } finally {
      s.close()
    }
  }
} 
开发者ID:lanshuijuntuan,项目名称:Java.util,代码行数:37,代码来源:RandomSocket.scala


示例19: MudBot

//设置package包名称以及导入依赖的类
package org.kirhgoff.munchkin

import java.net.Socket
import java.util.concurrent.Executors._
import java.util.concurrent.ThreadPoolExecutor

class MudBot(hostname: String, port: Int) {
  val executor:ThreadPoolExecutor =
    newFixedThreadPool(2).asInstanceOf[ThreadPoolExecutor]

  val socket = new Socket(hostname, port)
  val outputStream = socket.getOutputStream
  val inputStream = socket.getInputStream

  def stop() = {
    try { inputStream.close() } catch { case e:Exception => e.printStackTrace()}
    try { outputStream.close() } catch { case e:Exception => e.printStackTrace()}
    try { socket.close() } catch { case e:Exception => e.printStackTrace()}
  }

  def startLoop() = {
    val writer = new MudWriter(outputStream)
    val ai = new FalloutBot (writer)
    val inputReader = new UserInputReader(ai)
    val reader = new MudReader(inputStream, ai)

    executor.execute(reader)
    executor.execute(inputReader)

    while (executor.getActiveCount == 2) {
      Thread.sleep(1000)
    }
    println("system> Exiting")
    executor.shutdownNow()
    System.exit(0)
  }

  //def enterWarzone(): Unit = ???

  //def login(login: String, passwordPath: String): Unit = ???

} 
开发者ID:kirhgoff,项目名称:munchkin,代码行数:43,代码来源:MudBot.scala


示例20: SocketConnection

//设置package包名称以及导入依赖的类
package servicebus

import java.io.InputStreamReader
import java.net.{InetAddress, Socket}

import scala.io.BufferedSource


object SocketConnection {
  def connect(ip: String) {
    println("hey")
    val socket: Socket = new Socket(InetAddress.getByName(ip), 11000)
    println("wtf")
    val source: BufferedSource = new BufferedSource(socket.getInputStream)
    while (true) {
      val line: String = source.bufferedReader().readLine()
      println(line)
    }
  }

  def main(args: Array[String]): Unit = {
    SocketConnection.connect("51.4.231.251")
  }
} 
开发者ID:powergrid-loadbalancer,项目名称:pglb-backend,代码行数:25,代码来源:SocketConnection.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala PropertyChecks类代码示例发布时间:2022-05-23
下一篇:
Scala Closeable类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap