0

I write some scala code, which is used for shuffle.

The code is just like the following, but the serverSocket closed unexpected, the serverSocket will start(I observed using netsta), but after a while, it will be closed.

private val conManagerThread = new Thread("connection-manager-thread") {
override def run() = ConnectionManager.this.run()
}
conManagerThread.setDaemon(true)
conManagerThread.start()

def run() {
    val serverSocket = new ServerSocket(port, 0, InetAddress.getByName(Utils.localHostName))
    try{
        //while(!conManagerThread.isInterrupted) {
        while(true) {
            try {
                logInfo("start listening client ")
                val clientSocket = serverSocket.accept()
                logInfo("accept a client")
                serverPool.execute(new ServerConnection(clientSocket, id, onReceiveCallback)) //TODO: the conId maybe a remote id, so we should get it from the msg
            }
            catch {
                case e: Exception => logError("Error in serverSocket accept", e)
                logError("Error in serverSocket accept")
            }
       }
    }
    catch {
        case e: Exception => logError("Error in serverPool execute", e)
            logError("Error in serverPool execute")
    }
    finally{
        logInfo("=====\nserver closed\n=========")
    }

and the ServerConnection is like following:

class ServerConnection(client : Socket,  conId: ConnectionManagerId,
    onReceiveCallback: (BufferMessage, ConnectionManagerId) => Option[Message])
    extends Runnable with Logging{
    def run(){
        //some other code
    }
}
Djvu
  • 605
  • 1
  • 5
  • 18

1 Answers1

0

I think you have a problem because you have backlog set to 0 in your ServerSocket ctor, or because you didn't set ReusableAddress to true (most likely). And as far as I know it's a common practice to create ServerSocket first, and then bind it to port and do other stuff. I'd recommend you to create method that creates optional SereverSocket.

import scala.util.{Try, Success, Failure}

def socket(port: Int) = Try {
  val socket = new ServerSocket()
  socket.setReusableAddress(true)
  socket.bind(new InternetSocketAddress("localhost", port))
  socket
} match {
  case Success(s) => Some(s)
  case Failure(ex) =>
    logError("Error during ServerSocket creation", ex)
    None
}
ppopoff
  • 658
  • 7
  • 17