我写了一些scala代码,用于shuffle。
代码如下所示,但serverSocket关闭意外,serverSocket将启动(我观察使用netsta),但过了一会儿,它将被关闭。
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=========")
}
,ServerConnection如下:
class ServerConnection(client : Socket, conId: ConnectionManagerId,
onReceiveCallback: (BufferMessage, ConnectionManagerId) => Option[Message])
extends Runnable with Logging{
def run(){
//some other code
}
}
答案 0 :(得分:0)
我认为您遇到问题,因为您在ServerSocket ctor中将backlog设置为0,或者因为您没有将ReusableAddress设置为true(最有可能)。据我所知,首先创建ServerSocket是一种常见做法,然后将其绑定到端口并执行其他操作。 我建议你创建一个创建可选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
}