Create a gist now

Instantly share code, notes, and snippets.

Embed
A delegating javax.net.SocketFactory that enables Socket configuration
import javax.net.SocketFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.function.Consumer;
/**
* A {@link SocketFactory} that delegates calls. Sockets can be configured after creation by
* overriding {@link #configureSocket(java.net.Socket)}.
*/
public class DelegatingSocketFactory extends SocketFactory {
// copied from okhttp3 tests
private final SocketFactory delegate;
public DelegatingSocketFactory(SocketFactory delegate) {
this.delegate = delegate;
}
@Override public Socket createSocket() throws IOException {
Socket socket = delegate.createSocket();
return configureSocket(socket);
}
@Override public Socket createSocket(String host, int port) throws IOException {
Socket socket = delegate.createSocket(host, port);
return configureSocket(socket);
}
@Override public Socket createSocket(String host, int port, InetAddress localAddress,
int localPort) throws IOException {
Socket socket = delegate.createSocket(host, port, localAddress, localPort);
return configureSocket(socket);
}
@Override public Socket createSocket(InetAddress host, int port) throws IOException {
Socket socket = delegate.createSocket(host, port);
return configureSocket(socket);
}
@Override public Socket createSocket(InetAddress host, int port, InetAddress localAddress,
int localPort) throws IOException {
Socket socket = delegate.createSocket(host, port, localAddress, localPort);
return configureSocket(socket);
}
protected Socket configureSocket(Socket socket) throws IOException {
// No-op by default.
return socket;
}
public static SocketFactory custom() {
Consumer<Socket> config = HttpUtils.socketConfig;
return custom(config);
}
/**
* Configure sockets using a {@link Consumer}
* <pre>
* Sample consumer:
* {@code public static Consumer<Socket> socketConfig = CheckedConsumer.unchecked(socket -> {
* socket.setReceiveBufferSize(1024 * 1024);
* socket.setTcpNoDelay(true);
* socket.setKeepAlive(true);
* socket.setReuseAddress(true);
* });
* }
* </pre>
* @param config
* @return
*/
public static SocketFactory custom(final Consumer<Socket> config) {
DelegatingSocketFactory factory = new DelegatingSocketFactory(getDefault()) {
@Override
protected Socket configureSocket(Socket socket) throws IOException {
config.accept(socket);
return socket;
}
};
return factory;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment