Skip to content

Commit

Permalink
WebSocket: Configurable timeouts.
Browse files Browse the repository at this point in the history
  • Loading branch information
e3ndr committed Nov 23, 2024
1 parent 2706d51 commit bd15872
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 10 deletions.
2 changes: 1 addition & 1 deletion websocket/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ client.setListener(new WebSocketListener() {
System.out.println("Closed");
}
});
client.connect();
client.connect(10_000, 5_000);

Scanner in = new Scanner(System.in);
while (true) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import javax.net.SocketFactory;
Expand All @@ -30,8 +29,6 @@
import lombok.Setter;

public class WebSocketClient implements Closeable {
private static final long PING_INTERVAL = TimeUnit.SECONDS.toMillis(5);

private final ReentrantLock lock = new ReentrantLock();

private @Setter int maxPayloadLength = 16 /*mb*/ * 1024 * 1024;
Expand Down Expand Up @@ -128,12 +125,12 @@ public <T> T attachment() {
return (T) this.attachment;
}

private void doPing() {
private void doPing(long timeout) {
try {
while (true) {
byte[] someBytes = PrimitiveMarshall.BIG_ENDIAN.longToBytes(System.currentTimeMillis());
this.sendFrame(true, WebsocketOpCode.PING, someBytes);
Thread.sleep(PING_INTERVAL);
Thread.sleep(timeout);
}
} catch (Exception ignored) {
this.readThread.interrupt();
Expand Down Expand Up @@ -289,15 +286,15 @@ private void doRead() {
}
}

public void connect() throws IOException {
public void connect(long timeout, long pingInterval) throws IOException {
this.lock.lock();
try {
if (this.state != State.NEVER_CONNECTED) throw new IllegalStateException("Current state is: " + this.state);
this.state = State.CONNECTING;

this.socket = this.socketFactory.createSocket();
this.socket.connect(this.address, (int) (PING_INTERVAL * 4));
this.socket.setSoTimeout((int) (PING_INTERVAL * 2));
this.socket.connect(this.address, (int) timeout);
this.socket.setSoTimeout((int) timeout);
this.socket.setTcpNoDelay(true);

this.inputStream = new OverzealousInputStream(this.socket.getInputStream());
Expand Down Expand Up @@ -331,7 +328,7 @@ public void connect() throws IOException {
this.state = State.CONNECTED;
this.listener.onOpen(this, headers, acceptedProtocol);

this.pingThread = this.threadFactory.newThread(this::doPing);
this.pingThread = this.threadFactory.newThread(() -> this.doPing(pingInterval));
this.pingThread.setName("WebSocket Client Ping Thread - " + this.address);
this.pingThread.start();

Expand Down

0 comments on commit bd15872

Please sign in to comment.