List of usage examples for java.net Socket isClosed
public boolean isClosed()
From source file:org.apache.stratos.python.cartridge.agent.test.PythonAgentTestManager.java
/** * Start server socket// ww w.ja va 2 s. c o m * * @param port */ protected void startServerSocket(final int port) { Thread socketThread = new Thread(new Runnable() { @Override public void run() { while (true) { // do this infinitely until test is complete try { ServerSocket serverSocket = new ServerSocket(port); serverSocketMap.put(port, serverSocket); log.info("Server socket started on port: " + port); Socket socket = serverSocket.accept(); log.info("Client connected to [port] " + port); InputStream is = socket.getInputStream(); byte[] buffer = new byte[1024]; int read; while (true) { if (socket.isClosed()) { log.info("Socket for [port] " + port + " has been closed."); break; } if ((read = is.read(buffer)) != -1) { String output = new String(buffer, 0, read); log.info("Message received for [port] " + port + ", [message] " + output); } } } catch (IOException e) { String message = "Could not start server socket: [port] " + port; log.error(message, e); throw new RuntimeException(message, e); } } } }); socketThread.start(); }
From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java
/** * Sends 2 concurrent messages on a shared connection. The GW single threads * these requests. The first will timeout; the second should receive its * own response, not that for the first. * @throws Exception//from w ww .ja v a 2 s . c o m */ private void testGoodNetGWTimeoutGuts(final int port, AbstractConnectionFactory ccf) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); /* * The payload of the last message received by the remote side; * used to verify the correct response is received. */ final AtomicReference<String> lastReceived = new AtomicReference<String>(); final CountDownLatch serverLatch = new CountDownLatch(2); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown(); int i = 0; while (!done.get()) { Socket socket = server.accept(); i++; while (!socket.isClosed()) { try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String request = (String) ois.readObject(); logger.debug("Read " + request); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); if (i < 2) { Thread.sleep(1000); } oos.writeObject(request.replace("Test", "Reply")); logger.debug("Replied to " + request); lastReceived.set(request); serverLatch.countDown(); } catch (IOException e) { logger.debug("error on write " + e.getClass().getSimpleName()); socket.close(); } } } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); final TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(ccf); gateway.setRequestTimeout(Integer.MAX_VALUE); QueueChannel replyChannel = new QueueChannel(); gateway.setRequiresReply(true); gateway.setOutputChannel(replyChannel); gateway.setRemoteTimeout(500); @SuppressWarnings("unchecked") Future<Integer>[] results = new Future[2]; for (int i = 0; i < 2; i++) { final int j = i; results[j] = (Executors.newSingleThreadExecutor().submit(new Callable<Integer>() { public Integer call() throws Exception { // increase the timeout after the first send if (j > 0) { gateway.setRemoteTimeout(5000); } gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build()); return j; } })); Thread.sleep(50); } // wait until the server side has processed both requests assertTrue(serverLatch.await(10, TimeUnit.SECONDS)); List<String> replies = new ArrayList<String>(); int timeouts = 0; for (int i = 0; i < 2; i++) { try { int result = results[i].get(); String reply = (String) replyChannel.receive(1000).getPayload(); logger.debug(i + " got " + result + " " + reply); replies.add(reply); } catch (ExecutionException e) { if (timeouts >= 2) { fail("Unexpected " + e.getMessage()); } else { assertNotNull(e.getCause()); assertTrue(e.getCause() instanceof MessageTimeoutException); } timeouts++; continue; } } assertEquals("Expected exactly one ExecutionException", 1, timeouts); assertEquals(1, replies.size()); assertEquals(lastReceived.get().replace("Test", "Reply"), replies.get(0)); done.set(true); assertEquals(0, TestUtils.getPropertyValue(gateway, "pendingReplies", Map.class).size()); gateway.stop(); }
From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java
/** * Retrieves all active checks configured in the server. * /* w w w . j a va 2s .c o m*/ * @param hostname * @return List<ActiveCheck> * @throws IOException */ public List<ActiveCheck> getActiveChecks(String hostname) throws IOException { List<ActiveCheck> list = new ArrayList<ActiveCheck>(); Socket socket = null; OutputStream out = null; BufferedReader brin = null; try { socket = new Socket(zabbixServer, zabbixPort); socket.setSoTimeout(TIMEOUT); out = socket.getOutputStream(); brin = new BufferedReader(new InputStreamReader(socket.getInputStream())); // send request to Zabbix server and wait for the list of items to be returned out.write(createGetActiveChecksRequest(hostname)); while (!socket.isClosed()) { String line = brin.readLine(); if (line == null) break; // all active checks received if (line.startsWith(ZBX_EOF)) break; list.add(parseActiveCheck(hostname, line)); } } finally { if (brin != null) { brin.close(); } if (out != null) { out.close(); } if (socket != null) { socket.close(); } } return list; }
From source file:org.unitime.timetable.solver.remote.RemoteSolverServerProxy.java
public Socket leaseConnection() throws Exception { synchronized (iSocketPool) { if (iSocketPool.isEmpty() && iSocketPool.size() + iLeasedSockets.size() < sMaxPoolSize) { Socket socket = ConnectionFactory.getSocketFactory().createSocket(iAddress.getHostName(), iPort); ;//from w ww .j a va 2 s .c om sLog.debug("-- connection " + this + "@" + socket.getLocalPort() + " created"); iLeasedSockets.addElement(socket); return socket; } while (true) { if (!iSocketPool.isEmpty()) { Socket socket = (Socket) iSocketPool.firstElement(); iSocketPool.removeElement(socket); if (socket.isClosed()) { socket = ConnectionFactory.getSocketFactory().createSocket(iAddress.getHostName(), iPort); ; sLog.debug("-- connection " + this + "@" + socket.getLocalPort() + " created (reconnect)"); } iLeasedSockets.addElement(socket); return socket; } iSocketPool.wait(); } } }
From source file:com.android.emailcommon.utility.SSLSocketFactory.java
/** * Checks whether a socket connection is secure. * This factory creates TLS/SSL socket connections * which, by default, are considered secure. * <br/>/* w w w .j av a2 s .co m*/ * Derived classes may override this method to perform * runtime checks, for example based on the cypher suite. * * @param sock the connected socket * * @return <code>true</code> * * @throws IllegalArgumentException if the argument is invalid */ @Override public boolean isSecure(Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null."); } // This instanceof check is in line with createSocket() above. if (!(sock instanceof SSLSocket)) { throw new IllegalArgumentException("Socket not created by this factory."); } // This check is performed last since it calls the argument object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed."); } return true; }
From source file:org.wso2.carbon.automation.extensions.servers.webserver.SimpleWebServer.java
public void run() { ServerSocket serverSocket = null; Socket connectionSocket = null; try {//from www.j ava 2 s. co m log.info("Trying to bind to localhost on port " + Integer.toString(port) + "..."); serverSocket = new ServerSocket(port); log.info("Running Simple WebServer!\n"); connectionSocket = serverSocket.accept(); connectionSocket.setSoTimeout(30000); //go in a infinite loop, wait for connections, process request, send response while (running) { log.info("\nReady, Waiting for requests...\n"); try { //this call waits/blocks until someone connects to the port we BufferedReader input; if (!connectionSocket.isClosed()) { InetAddress client = connectionSocket.getInetAddress(); log.info(client.getHostName() + " connected to server.\n"); input = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream(), Charset.defaultCharset())); if (input.ready()) { DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream()); httpHandler(input, output); } } //Prepare a outputStream. This will be used sending back our response //(header + requested file) to the client. } catch (Exception e) { //catch any errors, and print them log.info("\nError:" + e.getMessage()); running = false; } } } catch (Exception e) { log.error("\nFatal Error:" + e.getMessage()); running = false; } finally { try { if (connectionSocket != null) { connectionSocket.close(); serverSocket.close(); } } catch (IOException e) { log.error("Error while shutting down server sockets", e); } } }
From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java
private TcpConnectionSupport mockedTcpNetConnection() throws IOException { Socket socket = mock(Socket.class); when(socket.isClosed()).thenReturn(true); // closed when next retrieved OutputStream stream = mock(OutputStream.class); doThrow(new IOException("Foo")).when(stream).write(any(byte[].class), anyInt(), anyInt()); when(socket.getOutputStream()).thenReturn(stream); TcpNetConnection conn = new TcpNetConnection(socket, false, false, new ApplicationEventPublisher() { @Override/*from ww w.java 2s.c o m*/ public void publishEvent(ApplicationEvent event) { } @Override public void publishEvent(Object event) { } }, "foo"); conn.setMapper(new TcpMessageMapper()); conn.setSerializer(new ByteArrayCrLfSerializer()); return conn; }
From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java
/** * Checks whether a socket connection is secure. * This factory creates TLS/SSL socket connections * which, by default, are considered secure. * <br/>/*from ww w.j a v a 2 s .c o m*/ * Derived classes may override this method to perform * runtime checks, for example based on the cypher suite. * * @param sock the connected socket * * @return <code>true</code> * * @throws IllegalArgumentException if the argument is invalid */ public boolean isSecure(final Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null"); } // This instanceof check is in line with createSocket() above. if (!(sock instanceof SSLSocket)) { throw new IllegalArgumentException("Socket not created by this factory"); } // This check is performed last since it calls the argument object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed"); } return true; }
From source file:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java
/** * Start server socket/*ww w . j a va 2 s. co m*/ * * @param port Port number of server socket to be started */ protected void startServerSocket(final int port) { Thread socketThread = new Thread(new Runnable() { @Override public void run() { try { ServerSocket serverSocket = new ServerSocket(port); serverSocketMap.put(port, serverSocket); log.info("Server socket started on port: " + port); Socket socket = serverSocket.accept(); log.info("Client connected to [port] " + port); InputStream is = socket.getInputStream(); byte[] buffer = new byte[1024]; int read; while (!socket.isClosed()) { if ((read = is.read(buffer)) != -1) { String output = new String(buffer, 0, read); log.info("Message received for [port] " + port + ", [message] " + output); } } } catch (IOException e) { String message = "Could not start server socket: [port] " + port; log.error(message, e); throw new RuntimeException(message, e); } } }); socketThread.start(); }
From source file:com.isecpartners.gizmo.HttpRequest.java
void passThroughAllBits() { try {//www .j a v a 2 s. c o m Socket destinationHost = new Socket(host, port); byte[] buf = new byte[1024]; boolean didNothing = true; while (!this.sock.isClosed() && !destinationHost.isClosed()) { didNothing = true; if (sock.getInputStream().available() > 0) { int b = sock.getInputStream().read(buf); destinationHost.getOutputStream().write(buf, 0, b); didNothing = false; } if (destinationHost.getInputStream().available() > 0) { int b = destinationHost.getInputStream().read(buf); sock.getOutputStream().write(buf, 0, b); didNothing = false; } if (didNothing) { try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } } } this.sock.close(); destinationHost.close(); } catch (UnknownHostException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } }