如何在后台线程中启动服务器,并知道服务器在启动时没有抛出异常? [英] How can I start a server in a background thread and know that the server did not throw exception on startup?
问题描述
我有一个封装服务器套接字的类,即服务器功能。
类的接口是:
I have a class which encapsulates a Server Socket i.e. a server functionality.
The interface of the class is:
class Server{
public void start();
public void stop();
}
开始如下:
public void start(){
ExecutorService tp = Executors.newSingleThreadExecutor();
while(!stop){
try {
Socket clientConnection = serverSocket.accept();
tp.execute(new ClientProcessor(clientConnection));
} catch (IOException e) {
stop = true;
}
}
我不知道如何开始这个我的意思是我需要从后台线程启动服务器,所以我想到了以下内容:
I have trouble figuring out how I would start this without blocing my main
.
I mean I need to start the server from a background thread so I thought of the following:
ExecutorService tp2 = Executors.newSingleThreadExecutor();
tp.submit(new Runnable(){
public void run(){
Server s = new Server();
s.start();
}
});
}
但我想要的是知道服务器启动,例外。我该如何做?
I.e。我如何从我的主
线程知道后台服务器开始正常,所以我可以继续其余的操作?
But what I want is to know that the server started and did not throw an exception. How can I do that?
I.e. how can I know from my main
thread that the background server started fine and so I can continue with the rest actions?
推荐答案
启动服务器。
等一下。
尝试在本地堆栈上连接到它。如果连接成功,您将获得胜利 - 只需关闭临时连接。
Start the server. Wait a bit. Try to connect to it on the local stack. If the connect succeeds, you have a winner - just close the temp connection.
这篇关于如何在后台线程中启动服务器,并知道服务器在启动时没有抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!