Skip to content

Commit 1c7162d

Browse files
committed
Try to stabilize SocketUtil
1 parent 9193048 commit 1c7162d

3 files changed

Lines changed: 13 additions & 12 deletions

File tree

src/test/java/org/java_websocket/issues/Issue879Test.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public class Issue879Test {
5757
@Timeout(10000)
5858
@ParameterizedTest()
5959
@MethodSource("data")
60-
public void QuickStopTest(int numberOfConnections) throws IOException, InterruptedException, URISyntaxException {
60+
public void QuickStopTest(int numberOfConnections) throws InterruptedException, URISyntaxException {
6161
final boolean[] wasBindException = {false};
6262
final boolean[] wasConcurrentException = new boolean[1];
6363
final CountDownLatch countDownLatch = new CountDownLatch(1);

src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public class ProtocolHandshakeRejectionTest {
5858
private int port;
5959

6060
@BeforeEach
61-
public void startServer() throws Exception {
61+
public void startServer() {
6262
port = SocketUtil.getAvailablePort();
6363
thread = new Thread(
6464
new Runnable() {
@@ -488,6 +488,9 @@ public void testHandshakeRejectionTestCase29() throws Exception {
488488
}
489489

490490
private void testProtocolRejection(int i, Draft_6455 draft) throws Exception {
491+
do {
492+
Thread.sleep(10);
493+
} while(serverSocket == null || !serverSocket.isBound());
491494
final int finalI = i;
492495
final CountDownLatch countDownLatch = new CountDownLatch(1);
493496
final WebSocketClient webSocketClient = new WebSocketClient(

src/test/java/org/java_websocket/util/SocketUtil.java

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,13 @@
3030

3131
public class SocketUtil {
3232

33-
public static int getAvailablePort() throws IOException {
34-
ServerSocket srv = null;
35-
try {
36-
srv = new ServerSocket(0);
37-
return srv.getLocalPort();
38-
} finally {
39-
if (srv != null) {
40-
srv.close();
41-
}
33+
public static int getAvailablePort() {
34+
while (true) {
35+
try (ServerSocket srv = new ServerSocket(0)) {
36+
return srv.getLocalPort();
37+
} catch (IOException e) {
38+
// Ignore
39+
}
40+
}
4241
}
43-
}
4442
}

0 commit comments

Comments
 (0)