summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/util/SocketConnection.scala
blob: 57b2b631005d027ac0fbd64a64737e224ce01ad6 (plain) (blame)
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
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

// $Id$

package scala.tools.util

import java.io.{PrintWriter, InputStreamReader, BufferedReader}
import java.io.IOException
import java.net.{Socket, InetAddress}
import java.net.UnknownHostException

/** This class implements the connection to the server.
 *
 *  @author Martin Odersky
 *  @version 1.0
 */
class SocketConnection(hostname: String, port: Int) {

  def this(port: Int) = this(InetAddress.getLocalHost().getHostName(), port)

  private var socket: Socket = _
  var out: PrintWriter = _
  var in: BufferedReader = _
  var errorMessage: String = _

  def open(): Boolean = {
    try {
      socket = new Socket(hostname, port)
      out = new PrintWriter(socket.getOutputStream(), true)
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
      true
    } catch {
      case e: UnknownHostException =>
        errorMessage = "Don't know about host: " + hostname + "."
        false
      case e: IOException =>
        errorMessage = "Couldn't get I/O for the connection to: " + hostname + "."
        false
    }
  }

  def close() {
    in.close()
    out.close()
    socket.close()
  }
}