【发布时间】:2018-04-25 02:58:52
【问题描述】:
我有一个客户端,我想尝试持续连接到服务器,直到建立连接(即,直到我启动服务器)。
clientSocket = new Socket();
while (!clientSocket.isConnected()) {
try {
clientSocket.connect(new InetSocketAddress(serverAddress, serverPort));
} catch (IOException e) {
e.printStackTrace();
}
// sleep prevents a billion SocketExceptions from being printed,
// and hopefully stops the server from thinking it's getting DOS'd
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
第一次尝试后,我得到了ConnectionException;预期的,因为没有什么可以连接的。然而,在那之后,我开始收到SocketException: Socket closed,这对我来说没有意义,因为clientSocket.isClosed() 在connect() 调用之前和之后总是返回false。
我应该如何更改我的代码以获得我需要的功能?
【问题讨论】:
-
将您的
new Socket移动到重试循环中。不要重复使用损坏的实例。 -
天哪,非常感谢。我已经为此拉头发太久了。只是证明解决方案的简单性与令人沮丧的程度成反比。