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


Scala ServerSocket类代码示例

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


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

示例1: Server

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

import java.net.ServerSocket
import java.util.concurrent.{ExecutorService, Executors}

import sh.webserver.request.Request

import scala.annotation.tailrec

class Server(port: Int) {
  def start() {
    val server = new ServerSocket(port)
    val pool = Executors.newFixedThreadPool(8)
    listen(server, pool)
  }

  @tailrec
  private def listen(server : ServerSocket,pool : ExecutorService) {
    val socket = server.accept()
    pool.execute(new RequestHandler(socket))
    listen(server, pool)
  }
} 
开发者ID:stefan-hering,项目名称:scalaserver,代码行数:24,代码来源:Server.scala

示例2: AGWPEConnectorSpec

//设置package包名称以及导入依赖的类
package com.softwaremill.modemconnector.agwpe

import java.net.ServerSocket

import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}

class AGWPEConnectorSpec extends FlatSpec with Matchers with BeforeAndAfterEach {

  var server: ServerSocket = _

  override def beforeEach(): Unit = {
    server = new ServerSocket(AGWPESettings.port)
  }

  override def afterEach(): Unit = {
    server.close()
  }


  "An AGWPEConnector" should "be created with configuration settings as default" in {
    //when
    val connector: AGWPEConnector = new AGWPEConnector()
    //then
    connector.host shouldEqual "127.0.0.1"
    connector.port shouldEqual 8000
    connector.timeout shouldEqual 3000
  }

  "An AGWPEConnector" should "be created with configuration settings as constructor arguments" in {
    //given
    val host: String = "127.0.0.1"
    val port: Int = 8000
    val timeout: Int = 1000
    //when
    val connector: AGWPEConnector = new AGWPEConnector(host, port, timeout)
    //then
    connector.host shouldEqual host
    connector.port shouldEqual port
    connector.timeout shouldEqual timeout
  }
} 
开发者ID:softwaremill,项目名称:modem-connector,代码行数:42,代码来源:AGWPEConnectorSpec.scala

示例3: T02_RandomLogger

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

import java.io.PrintWriter
import java.net.ServerSocket

import scala.collection.mutable


object T02_RandomLogger {

  def generateContent(index: Int): String = {
    import scala.collection.mutable.ListBuffer
    var charList = ListBuffer[Char]()
    for (i <- 65 to 90) {
      charList += i.toChar
    }
    val charArray = charList.toArray
    charArray(index).toString
  }

  def index = {
    import java.util.Random
    val rand = new Random
    rand.nextInt(7)
  }

  def main(args: Array[String]) {
    var port = 9999
    var sec = 1000l
    val map = new mutable.HashMap[String,Int]()
    if (args.length >= 2) {
      port = args(0).toInt
      sec = args(1).toLong
    }
    println("listening:" + port)
    val listener = new ServerSocket(port)
    while (true) {
      println("waiting...")
      val socket = listener.accept()
      println("accept:" + socket)
      new Thread() {
        override def run = {
          println("got client:" + socket.getInetAddress)
          val out = new PrintWriter(socket.getOutputStream, true)
          while (true) {
            Thread.sleep(sec)
            val content = generateContent(index)
            map.put(content,map.getOrElse(content,0)+1);
            out.write(content+"\n")
            out.flush()
            println(map)
          }
          socket.close()
        }
      }.start()
    }
  }
} 
开发者ID:IMJIU,项目名称:Spark1.6,代码行数:59,代码来源:T02_RandomLogger.scala

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

示例5: before

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

import java.net.ServerSocket
import java.nio.file.Files
import java.util.Properties

import _root_.kafka.server.KafkaConfig
import _root_.kafka.server.KafkaServerStartable
import org.apache.curator.test.TestingServer
import org.specs2.mutable.BeforeAfter
import org.specs2.specification.Scope

trait SimpleKafkaScope extends Scope with BeforeAfter{
  val zkServer = new TestingServer()
  val socket = new ServerSocket(0)
  val port = socket.getLocalPort.toString
  println(s"'port' looks like: $port")
  socket.close()
  val tmpDir = Files.createTempDirectory("kafka-test-logs")

  val serverProps = new Properties()
  serverProps.put("broker.id", port)
  serverProps.put("log.dirs", tmpDir.toAbsolutePath.toString)
  serverProps.put("host.name", "localhost")
  serverProps.put("zookeeper.connect", zkServer.getConnectString)
  serverProps.put("port", port)

  val config = new KafkaConfig(serverProps)
  val kafkaServer = new KafkaServerStartable(config)

  override def before: Unit = {
    kafkaServer.startup()
  }

  override def after: Unit = {
    kafkaServer.shutdown()
    zkServer.close()
    zkServer.stop()
  }

  println("zkServer: " + zkServer.getConnectString)
  println("Kafka broker port: " + port)
} 
开发者ID:ciaran-,项目名称:specs2-kafka,代码行数:44,代码来源:SimpleKafkaScope.scala

示例6: getHostIPFromVM

//设置package包名称以及导入依赖的类
package hk.edu.polyu.datamining.pamap2.virtual

import java.io.PrintWriter
import java.net.{ServerSocket, Socket}

import com.typesafe.config.ConfigFactory

import scala.io.Source
import scala.util.control.Breaks


  def getHostIPFromVM: String = {
    println(s"waiting host connection on port $guest_port")
    val serverSocket = new ServerSocket(guest_port)
    var hostIP: String = null
    val loop = new Breaks()
    loop.breakable({
      while (true) {
        try {
          val socket = serverSocket.accept()
          val in = Source.fromInputStream(socket.getInputStream)
          hostIP = in.getLines().toIndexedSeq(0)
          in.close()
          socket.close()
          if (hostIP != null)
            loop.break()
        } catch {
          case e: Exception => println(e)
        }
      }
    })
    println(s"resolved host ip : $hostIP")
    hostIP
  }

} 
开发者ID:polyu-datamining-2016,项目名称:data-mining-pamap2,代码行数:37,代码来源:VirtualNetworkHelper.scala

示例7: WebPageLogsGenerator

//设置package包名称以及导入依赖的类
import java.io.IOException
import java.io.PrintWriter
import java.net.ServerSocket
import java.net.Socket
import java.util.Date
import scala.util.Random

object WebPageLogsGenerator extends App {

  val ids = (1 to 10).toList
  val pages = List("/", "/login", "/profile", "/dashboard", "/profile/edit")

  val listener = new ServerSocket(9999)
  var socket: Socket = null
  try {
    socket = listener.accept();
    while (true) {
      val out: PrintWriter = new PrintWriter(socket.getOutputStream(), true);
      out.println(generateLog())
      Thread.sleep(args(0).toInt)

    }
  } finally {
    socket.close();
    listener.close();
  }

  def generateLog(): String = {
    val date  = new Date().toString
    val id = ids((System.nanoTime % ids.length).toInt).toString
    val page = pages((System.nanoTime % pages.length).toInt).toString
    s"$date - $id - $page"
  }
} 
开发者ID:rabbitonweb,项目名称:spark-workshop,代码行数:35,代码来源:WebPageLogsGenerator.scala

示例8: LoanPattern

//设置package包名称以及导入依赖的类
package io.sweetheart.examples.pis.abstractMembers

import java.io.PrintWriter
import java.net.ServerSocket
import java.util.Date

object LoanPattern {
  def using[T <: { def close(): Unit }, S](obj: T)
                (operation: T => S): Unit = {
    val result = operation(obj)
    obj.close();
    result
  }

  def main(args: Array[String]): Unit = {
    using(new PrintWriter("date.txt")) { writer =>
      writer.println(new Date)
    }

    using (new ServerSocket(9999)) { serverSocket =>
      println("listening on port 9999....")

      using (serverSocket.accept()) { socket =>
        socket.getOutputStream.write("hello, world\n".getBytes)
      }
    }
  }
} 
开发者ID:zzragida,项目名称:ScalaExamples,代码行数:29,代码来源:LoanPattern.scala

示例9: jmxConfig

//设置package包名称以及导入依赖的类
package eu.shiftforward.apso.profiling

import java.net.ServerSocket

import com.j256.simplejmx.server.JmxServer
import eu.shiftforward.apso.Logging

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

trait SimpleJmx extends Logging {

  def jmxConfig: config.Jmx

  private lazy val jmxHost = jmxConfig.host
  private lazy val jmxPort = jmxConfig.port

  private def startJmx(port: Option[Int] = None) = {
    def randomPort = {
      val s = new ServerSocket(0)
      val p = s.getLocalPort
      s.close()
      p
    }

    val jmx = new JmxServer(port.getOrElse(randomPort))
    jmx.start()
    jmx
  }

  // start a properly configured JMX server. When behind a firewall, both ports `jmxPort` (the RMI
  // registry port) and `jmxPort + 1` (the RMI server port) need to be open. Connections are
  // established through port `jmxPort`.
  // In the event of a binding failure to port `jmxPort`, a retry is performed with a random port.
  jmxHost.foreach { host => System.setProperty("java.rmi.server.hostname", host) }
  val jmxServer = Try(startJmx(jmxPort)).recover { case _ => startJmx() }

  jmxServer match {
    case Success(jmx) =>
      log.info("Bound JMX on port {}", jmx.getServerPort)
      sys.addShutdownHook(jmx.stop())

    case Failure(ex) =>
      log.warn("Could not start JMX server", ex)
  }
} 
开发者ID:ShiftForward,项目名称:apso,代码行数:46,代码来源:SimpleJmx.scala

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

示例11: PortFinder

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

import java.net.ServerSocket

object PortFinder {
  def getFreePort = {
    val socket = new ServerSocket(0) {
      setReuseAddress(true)
    }
    val port = socket.getLocalPort
    socket.close
    port
  }
} 
开发者ID:kelveden,项目名称:rest-driver-scala,代码行数:15,代码来源:PortFinder.scala

示例12: WireMockHelper

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

import java.net.ServerSocket
import java.util.UUID

import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.matching.RequestPattern._
import com.github.tomakehurst.wiremock.verification.LoggedRequest
import integration.helper.FakeApplicationHelper.withApplication
import play.api.test.FakeApplication

object WireMockHelper {

  def findCapturedRequest(server: WireMockServer): LoggedRequest = {
    server.findRequestsMatching(everything()).getRequests.get(0)
  }

  def withAppAndMock(app: FakeApplication, server: WireMockServer, call: () => Unit): Unit = {
    withApplication(app) {
      () => withWireMock(server) {
        () => {
          call()
        }
      }
    }
  }

  def randomUri: String = {
    "/" + UUID.randomUUID()
  }


  def withWireMock(server: WireMockServer)(call: () => Unit): Unit = {
    server.start()
    try {
      call()
    } finally {
      server.shutdownServer()
    }
  }


  def freePort(): Int = {
    val socket = new ServerSocket(0)
    val port = socket.getLocalPort
    socket.close()
    port
  }

} 
开发者ID:innoq,项目名称:docster,代码行数:51,代码来源:WireMockHelper.scala

示例13: Utils

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

import java.net.ServerSocket

object Utils {
  final val noLeadgerId: Int = -1

  def bytesToLongsArray(bytes: Array[Byte]): Array[Long] = {
    val buffer = java.nio.ByteBuffer
      .allocate(bytes.length)
      .put(bytes)
    buffer.flip()

    val size =  bytes.length / java.lang.Long.BYTES
    val longs = Array.fill[Long](size)(buffer.getLong)

    longs
  }

  def bytesToIntsArray(bytes: Array[Byte]): Array[Int] = {
    val buffer = java.nio.ByteBuffer
      .allocate(bytes.length)
      .put(bytes)
    buffer.flip()

    val size = bytes.length / java.lang.Integer.BYTES
    val ints = Array.fill[Int](size)(buffer.getInt)

    ints
  }

  def longArrayToBytes(longs: Array[Long]): Array[Byte] = {
    val buffer = java.nio.ByteBuffer.allocate(
      longs.length * java.lang.Long.BYTES
    )
    longs.foreach(longValue => buffer.putLong(longValue))
    buffer.array()
  }

  def getRandomPort: Int = {
    scala.util.Try {
      val server = new ServerSocket(0)
      val port = server.getLocalPort
      server.close()
      port
    } match {
      case scala.util.Success(port) =>
        port
      case scala.util.Failure(throwable: Throwable) =>
        throw throwable
    }
  }
} 
开发者ID:bwsw,项目名称:bookkeeper-tutorial-scala,代码行数:54,代码来源:Utils.scala

示例14: configureClient

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

import com.twitter.finagle.Mysql
import com.twitter.finagle.mysql._
import com.twitter.util.NonFatal
import java.io.{File, FileInputStream}
import java.net.{ServerSocket, BindException}
import java.util.logging.{Level, Logger}
import java.util.Properties

trait IntegrationClient {
  private val logger = Logger.getLogger("integration-client")

  // Check if default mysql port is available.
  val isPortAvailable = try {
    val socket = new ServerSocket(3306)
    socket.close()
    true
  } catch {
    case e: BindException => false
  }

  val propFile = new File(System.getProperty("user.home") +
    "/.finagle-mysql/integration-test.properties")

  val p = new Properties
  val propFileExists = try {
    val fis = new FileInputStream(propFile)
    p.load(fis)
    fis.close()
    true
  } catch {
    case NonFatal(e) =>
      logger.log(Level.WARNING, "Error loading integration.properties, skipping integration test")
      false
  }

  // It's likely that we can run this test
  // if a mysql instance is running and a valid
  // properties file is found which contains
  // mysql credentials.
  val isAvailable = !isPortAvailable && propFileExists

  protected def configureClient(username: String, password: String, db: String) = Mysql.client
    .withCredentials(username, password)
    .withDatabase(db)

  val client: Option[Client with Cursors] = if (isAvailable) {
    logger.log(Level.INFO, "Attempting to connect to mysqld @ localhost:3306")
    val username = p.getProperty("username", "<user>")
    val password = p.getProperty("password", null)
    val db = p.getProperty("db", "test")
    Some(configureClient(username, password, db)
      .newRichClient("localhost:3306"))
  } else {
    None
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:59,代码来源:IntegrationClient.scala

示例15: ThriftResponderSpec

//设置package包名称以及导入依赖的类
package io.livingston.ditto.thrift

import java.net.ServerSocket

import com.twitter.finagle.Thrift
import com.twitter.util.Await
import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}

class ThriftResponderSpec extends WordSpec with Matchers with BeforeAndAfter {
  val s = new ServerSocket(0)
  val port = s.getLocalPort
  s.close()
  val yaml =
    s"""
      |---
      |thrift:
      |- port: $port
      |  endpoints:
      |  - msg: "echoString"
      |    body: "gAEAAgAAAAplY2hvU3RyaW5nAAAAAAsAAAAAAAR0ZXN0AA=="
      |    latency:
      |      min: 10
      |      max: 100
    """.stripMargin

  val server = new ThriftResponder()

  before {
    server.apply(yaml)
  }

  after {
    server.close()
  }

  "Thrift config" should {
    "respond correctly to thrift requests" in {
      val client = Thrift.client.newIface[EchoService.FutureIface](s":$port")
      val response = Await.result(client.echoString("test"))
      response should be("test")
    }
  }
} 
开发者ID:scottlivingston,项目名称:ditto,代码行数:44,代码来源:ThriftResponderSpec.scala


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