1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2002-2010, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package scala.tools.util
import java.io.{ PrintWriter, BufferedOutputStream, BufferedReader, InputStreamReader, IOException }
import java.net.{ Socket, ServerSocket, SocketException, SocketTimeoutException }
object SocketServer
{
// After 30 idle minutes, politely exit.
// Should the port file disappear, and the clients
// therefore unable to contact this server instance,
// the process will just eventually terminate by itself.
val IdleTimeout = 1800000
val BufferSize = 10240
def bufferedReader(s: Socket) = new BufferedReader(new InputStreamReader(s.getInputStream()))
def bufferedOutput(s: Socket) = new BufferedOutputStream(s.getOutputStream, BufferSize)
}
import SocketServer._
/** The abstract class <code>SocketServer</code> implements the server
* communication for the fast Scala compiler.
*
* @author Martin Odersky
* @version 1.0
*/
abstract class SocketServer
{
def shutDown: Boolean
def session()
var out: PrintWriter = _
var in: BufferedReader = _
def fatal(msg: String): Nothing = {
System.err.println(msg)
system.exit(1)
}
private def warn(msg: String) {
System.err.println(msg)
}
// called after a timeout is detected,
// for SocketServer subclasses to perform
// some cleanup, if any
def timeout() {}
val serverSocket =
try new ServerSocket(0)
catch { case e: IOException => fatal("Could not listen on any port; exiting.") }
val port: Int = serverSocket.getLocalPort()
// @todo: this is going to be a prime candidate for ARM
def doSession(clientSocket: Socket) = {
out = new PrintWriter(clientSocket.getOutputStream(), true)
in = bufferedReader(clientSocket)
val bufout = bufferedOutput(clientSocket)
scala.Console.withOut(bufout) { session() }
bufout.close()
out.close()
in.close()
}
def run() {
def fail(s: String) = fatal(s format port)
try serverSocket setSoTimeout IdleTimeout catch {
case e: SocketException => fail("Could not set timeout on port: %d; exiting.")
}
try {
while (!shutDown) {
val clientSocket = try serverSocket.accept() catch {
case e: IOException => fail("Accept on port %d failed; exiting.")
}
doSession(clientSocket)
clientSocket.close()
}
}
catch {
case e: SocketTimeoutException =>
warn("Timeout elapsed with no requests from clients on port %d; exiting" format port)
timeout()
}
serverSocket.close()
}
}
|