alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (SocketConnection.scala)

This example Scala source code file (SocketConnection.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

bufferedreader, bufferedreader, couldn't, don't, i/o, int, int, io, ioexception, net, network, printwriter, socket, socket, string, string, unknownhostexception

The Scala SocketConnection.scala source code

/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2002-2011, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */


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()
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala SocketConnection.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.