本文整理汇总了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)
}
}
示例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
}
}
示例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()
}
}
}
示例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)
}
}
示例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)
}
示例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
}
}
示例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"
}
}
示例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)
}
}
}
}
示例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)
}
}
示例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()
}
}
}
示例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
}
}
示例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
}
}
示例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
}
}
}
示例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
}
}
示例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")
}
}
}