use of java.net.Socket in project grpc-java by grpc.
the class Platform method findPlatform.
/** Attempt to match the host runtime to a capable Platform implementation. */
private static Platform findPlatform() {
Provider sslProvider = GrpcUtil.IS_RESTRICTED_APPENGINE ? getAppEngineProvider() : getAndroidSecurityProvider();
if (sslProvider != null) {
// Attempt to find Android 2.3+ APIs.
OptionalMethod<Socket> setUseSessionTickets = new OptionalMethod<Socket>(null, "setUseSessionTickets", boolean.class);
OptionalMethod<Socket> setHostname = new OptionalMethod<Socket>(null, "setHostname", String.class);
Method trafficStatsTagSocket = null;
Method trafficStatsUntagSocket = null;
OptionalMethod<Socket> getAlpnSelectedProtocol = new OptionalMethod<Socket>(byte[].class, "getAlpnSelectedProtocol");
OptionalMethod<Socket> setAlpnProtocols = new OptionalMethod<Socket>(null, "setAlpnProtocols", byte[].class);
// Attempt to find Android 4.0+ APIs.
try {
Class<?> trafficStats = Class.forName("android.net.TrafficStats");
trafficStatsTagSocket = trafficStats.getMethod("tagSocket", Socket.class);
trafficStatsUntagSocket = trafficStats.getMethod("untagSocket", Socket.class);
} catch (ClassNotFoundException ignored) {
} catch (NoSuchMethodException ignored) {
}
return new Android(setUseSessionTickets, setHostname, trafficStatsTagSocket, trafficStatsUntagSocket, getAlpnSelectedProtocol, setAlpnProtocols, sslProvider);
}
try {
sslProvider = SSLContext.getDefault().getProvider();
} catch (NoSuchAlgorithmException nsae) {
throw new RuntimeException(nsae);
}
// Find Jetty's ALPN extension for OpenJDK.
try {
String negoClassName = "org.eclipse.jetty.alpn.ALPN";
Class<?> negoClass = Class.forName(negoClassName);
Class<?> providerClass = Class.forName(negoClassName + "$Provider");
Class<?> clientProviderClass = Class.forName(negoClassName + "$ClientProvider");
Class<?> serverProviderClass = Class.forName(negoClassName + "$ServerProvider");
Method putMethod = negoClass.getMethod("put", SSLSocket.class, providerClass);
Method getMethod = negoClass.getMethod("get", SSLSocket.class);
Method removeMethod = negoClass.getMethod("remove", SSLSocket.class);
return new JdkWithJettyBootPlatform(putMethod, getMethod, removeMethod, clientProviderClass, serverProviderClass, sslProvider);
} catch (ClassNotFoundException ignored) {
} catch (NoSuchMethodException ignored) {
}
return new Platform(sslProvider);
}
use of java.net.Socket in project hazelcast by hazelcast.
the class IOBalancerMemoryLeakTest method testMemoryLeak_with_SocketConnections.
@Test
public void testMemoryLeak_with_SocketConnections() throws IOException {
Config config = new Config();
config.getGroupConfig().setName(randomName());
config.setProperty(GroupProperty.IO_BALANCER_INTERVAL_SECONDS.getName(), "1");
HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
final Address address = instance.getCluster().getLocalMember().getAddress();
int threadCount = 10;
final int connectionCountPerThread = 100;
Runnable runnable = new Runnable() {
public void run() {
for (int i = 0; i < connectionCountPerThread; i++) {
Socket socket = null;
try {
socket = new Socket(address.getHost(), address.getPort());
socket.getOutputStream().write(Protocols.CLUSTER.getBytes());
sleepMillis(1000);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
threads[i] = new Thread(runnable);
threads[i].start();
}
assertJoinable(threads);
TcpIpConnectionManager connectionManager = (TcpIpConnectionManager) getConnectionManager(instance);
final IOBalancer ioBalancer = connectionManager.getIoBalancer();
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
LoadTracker inLoadTracker = ioBalancer.getInLoadTracker();
LoadTracker outLoadTracker = ioBalancer.getOutLoadTracker();
int inHandlerSize = inLoadTracker.getHandlers().size();
int outHandlerSize = outLoadTracker.getHandlers().size();
int inHandlerEventsCount = inLoadTracker.getHandlerEventsCounter().keySet().size();
int outHandlerEventsCount = outLoadTracker.getHandlerEventsCounter().keySet().size();
int inLastEventsCount = inLoadTracker.getLastEventCounter().keySet().size();
int outLastEventsCount = outLoadTracker.getLastEventCounter().keySet().size();
Assert.assertEquals(0, inHandlerSize);
Assert.assertEquals(0, outHandlerSize);
Assert.assertEquals(0, inHandlerEventsCount);
Assert.assertEquals(0, outHandlerEventsCount);
Assert.assertEquals(0, inLastEventsCount);
Assert.assertEquals(0, outLastEventsCount);
}
});
}
use of java.net.Socket in project hazelcast by hazelcast.
the class ConnectionTest method testDanglingSocketsOnTerminate.
private void testDanglingSocketsOnTerminate(boolean withSocketInterceptor) throws Exception {
final int port = 5701;
Config config = new Config();
config.getNetworkConfig().setPort(port).setPortAutoIncrement(false);
if (withSocketInterceptor) {
config.getNetworkConfig().setSocketInterceptorConfig(new SocketInterceptorConfig().setEnabled(true).setImplementation(new MemberSocketInterceptor() {
public void init(Properties properties) {
}
public void onAccept(Socket acceptedSocket) throws IOException {
}
public void onConnect(Socket connectedSocket) throws IOException {
}
}));
}
final HazelcastInstance hz = Hazelcast.newHazelcastInstance(config);
final int count = 100;
final CountDownLatch latch = new CountDownLatch(count);
final CountDownLatch ll = new CountDownLatch(1);
final AtomicInteger cc = new AtomicInteger();
new Thread() {
public void run() {
try {
ll.await(1, TimeUnit.MINUTES);
hz.getLifecycleService().terminate();
} catch (InterruptedException ignored) {
}
}
}.start();
final Collection<Socket> sockets = Collections.newSetFromMap(new ConcurrentHashMap<Socket, Boolean>());
final AtomicInteger k0 = new AtomicInteger();
final AtomicInteger k1 = new AtomicInteger();
for (int i = 0; i < count; i++) {
Runnable task = new Runnable() {
public void run() {
try {
if (cc.incrementAndGet() == count / 10) {
ll.countDown();
}
Socket socket = new Socket();
sockets.add(socket);
try {
socket.connect(new InetSocketAddress(port));
k0.incrementAndGet();
} catch (IOException e) {
k1.incrementAndGet();
}
OutputStream out = socket.getOutputStream();
out.write(Protocols.CLUSTER.getBytes());
out.flush();
socket.getInputStream().read();
} catch (IOException ignored) {
} finally {
latch.countDown();
}
}
};
Thread t = new Thread(task, "socket-thread-" + i);
t.setDaemon(true);
t.start();
}
try {
assertTrue(latch.await(1, TimeUnit.MINUTES));
} catch (AssertionError e) {
System.err.println(ThreadDumpGenerator.dumpAllThreads());
throw e;
} finally {
for (Socket socket : sockets) {
try {
socket.close();
} catch (Exception e) {
ignore(e);
}
}
}
}
use of java.net.Socket in project hazelcast by hazelcast.
the class ConnectionTest method testBlockedClientSockets.
@Test
public void testBlockedClientSockets() throws Exception {
final ServerSocket serverSocket = new ServerSocket(13131, 1);
final int count = 100;
final CountDownLatch latch = new CountDownLatch(count);
final AtomicInteger connected = new AtomicInteger();
final AtomicInteger cc = new AtomicInteger();
final Set<Socket> sockets = Collections.newSetFromMap(new ConcurrentHashMap<Socket, Boolean>());
final Thread st = new Thread("server-socket") {
public void run() {
while (!isInterrupted()) {
try {
Socket socket = serverSocket.accept();
sockets.add(socket);
} catch (IOException ignored) {
}
}
}
};
st.start();
final AtomicBoolean flag = new AtomicBoolean(false);
for (int i = 0; i < count; i++) {
final Socket clientSocket = new Socket();
Thread t = new Thread("client-socket-" + i) {
public void run() {
try {
if (cc.incrementAndGet() > count / 5 && Math.random() > .87f && flag.compareAndSet(false, true)) {
st.interrupt();
serverSocket.close();
try {
st.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Iterator<Socket> iter = sockets.iterator();
while (iter.hasNext()) {
Socket socket = iter.next();
socket.shutdownOutput();
socket.close();
iter.remove();
}
} else {
clientSocket.connect(new InetSocketAddress(13131));
connected.incrementAndGet();
clientSocket.getInputStream().read();
}
} catch (IOException ignored) {
} finally {
latch.countDown();
}
}
};
t.setDaemon(true);
t.start();
}
assertTrue(latch.await(1, TimeUnit.MINUTES));
}
use of java.net.Socket in project j2objc by google.
the class MockWebServer method play.
/**
* Starts the server, serves all enqueued requests, and shuts the server
* down.
*
* @param port the port to listen to, or 0 for any available port.
* Automated tests should always use port 0 to avoid flakiness when a
* specific port is unavailable.
*/
public void play(int port) throws IOException {
if (acceptExecutor != null) {
throw new IllegalStateException("play() already called");
}
// The acceptExecutor handles the Socket.accept() and hands each request off to the
// requestExecutor. It also handles shutdown.
acceptExecutor = Executors.newSingleThreadExecutor();
// The requestExecutor has a fixed number of worker threads. In order to get strict
// guarantees that requests are handled in the order in which they are accepted
// workerThreads should be set to 1.
requestExecutor = Executors.newFixedThreadPool(workerThreads);
serverSocket = new ServerSocket(port);
serverSocket.setReuseAddress(true);
this.port = serverSocket.getLocalPort();
acceptExecutor.execute(namedRunnable("MockWebServer-accept-" + port, new Runnable() {
public void run() {
try {
acceptConnections();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer connection failed", e);
}
/*
* This gnarly block of code will release all sockets and
* all thread, even if any close fails.
*/
try {
serverSocket.close();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer server socket close failed", e);
}
for (Iterator<Socket> s = openClientSockets.keySet().iterator(); s.hasNext(); ) {
try {
s.next().close();
s.remove();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer socket close failed", e);
}
}
try {
acceptExecutor.shutdown();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer acceptExecutor shutdown failed", e);
}
try {
requestExecutor.shutdown();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer requestExecutor shutdown failed", e);
}
}
private void acceptConnections() throws Exception {
while (true) {
Socket socket;
try {
socket = serverSocket.accept();
} catch (SocketException e) {
return;
}
SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
if (socketPolicy == DISCONNECT_AT_START) {
dispatchBookkeepingRequest(0, socket);
socket.close();
} else {
openClientSockets.put(socket, true);
serveConnection(socket);
}
}
}
}));
}
Aggregations