简单的scala套接字程序 - 只与一个客户端交谈?

时间:2015-08-08 13:16:10

标签: scala

我试图制作一个非常简单的scala套接字程序,它将回复"输出它从多个客户收到的任何输入

此程序确实有效,但仅适用于单个客户端。我认为这是因为执行总是在while(true)循环

import java.net._
import java.io._
import scala.io._


//println(util.Properties.versionString)

val server = new ServerSocket(9999)
println("initialized server")
val client = server.accept

while(true){

val in = new BufferedReader(new InputStreamReader(client.getInputStream)).readLine
val out = new PrintStream(client.getOutputStream)

println("Server received:" + in) // print out the input message
out.println("Message received")
out.flush


}

我已经尝试了

进行此修改

while(true){

    val client = server.accept

    val in = new BufferedReader(new InputStreamReader(client.getInputStream)).readLine
    val out = new PrintStream(client.getOutputStream)
    println("Server received:" + in)  

    }

但这确实超越了#34;回显单个消息

我希望多个客户端连接到套接字并不断接收输入内容的输出

2 个答案:

答案 0 :(得分:1)

基本上,您应该接受连接并为每个客户端创建一个新的Future。请注意隐式全局ExecutionContext可能会受到限制,您可能需要找到一个更适合您的用例的不同版本。

如果您需要更复杂的期货任务,可以使用Scala异步,但我认为这可能很好。

免责声明,我没有试过这个,但类似的东西可能有用(基于您的代码和the docs):

import scala.concurrent._
import ExecutionContext.Implicits.global
...

while(true){
    val client = server.accept
    Future {
        val inReader = new BufferedReader(new InputStreamReader(client.getInputStream))
        val out = new PrintStream(client.getOutputStream)
        do {
            val in = inReader.readLine
            println("Server received:" + in)
        } while (true/*or a better condition to close the connection */)
        client.close
    }
}

答案 1 :(得分:-1)

您可以在此处找到scala语言的示例:

[http://www.scala-lang.org/old/node/55][1]

这也是scala twitter学校的一个很好的例子,它适用于java库:

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

class NetworkService(port: Int, poolSize: Int) extends Runnable {
  val serverSocket = new ServerSocket(port)

  def run() {
    while (true) {
      // This will block until a connection comes in.
      val socket = serverSocket.accept()
      (new Handler(socket)).run()
    }
  }
}

class Handler(socket: Socket) extends Runnable {
  def message = (Thread.currentThread.getName() + "\n").getBytes

  def run() {
    socket.getOutputStream.write(message)
    socket.getOutputStream.close()
  }
}

(new NetworkService(2020, 2)).run