本文整理汇总了Scala中java.net.Socket类的典型用法代码示例。如果您正苦于以下问题:Scala Socket类的具体用法?Scala Socket怎么用?Scala Socket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Socket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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")
}
}
}
示例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() }
}
}
}
示例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()
}
}
示例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()
}
}
}
示例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)
}
}
}
}
示例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)
}
}
示例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()
}
}
}
示例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()
}
}
}
示例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)
}
}
示例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)
}
}
}
示例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:
示例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
}
}
示例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)
}
}
示例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()
}
}
示例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}]"))
}