Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow user to specify max number of pending connections to a server #1001

Merged
merged 2 commits into from Apr 23, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 29 additions & 4 deletions src/main/java/org/java_websocket/server/WebSocketServer.java
Expand Up @@ -26,9 +26,7 @@
package org.java_websocket.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedByInterruptException;
Expand Down Expand Up @@ -108,6 +106,13 @@ public abstract class WebSocketServer extends AbstractWebSocket implements Runna

private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory();

/**
* Attribute which allows you to configure the socket "backlog" parameter
* which determines how many client connections can be queued.
* @since 1.5.0
*/
private int maxPendingConnections = -1;

/**
* Creates a WebSocketServer that will attempt to
* listen on port <var>WebSocketImpl.DEFAULT_PORT</var>.
Expand Down Expand Up @@ -308,6 +313,26 @@ public List<Draft> getDraft() {
return Collections.unmodifiableList( drafts );
}

/**
* Set the requested maximum number of pending connections on the socket. The exact semantics are implementation
* specific. The value provided should be greater than 0. If it is less than or equal to 0, then
* an implementation specific default will be used. This option will be passed as "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)}
* @since 1.5.0
*/
public void setMaxPendingConnections(int numberOfConnections) {
maxPendingConnections = numberOfConnections;
}

/**
* Returns the currently configured maximum number of pending connections.
*
* @see #setMaxPendingConnections(int)
* @since 1.5.0
*/
public int getMaxPendingConnections() {
return maxPendingConnections;
}

// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
if (!doEnsureSingleThread()) {
Expand Down Expand Up @@ -505,7 +530,7 @@ private boolean doSetupSelectorAndServerThread() {
ServerSocket socket = server.socket();
socket.setReceiveBufferSize( WebSocketImpl.RCVBUF );
socket.setReuseAddress( isReuseAddr() );
socket.bind( address );
socket.bind( address, getMaxPendingConnections() );
selector = Selector.open();
server.register( selector, server.validOps() );
startConnectionLostTimer();
Expand Down