Java Code Examples for java.net.Socket#close()

The following examples show how to use java.net.Socket#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JobXAgent.java    From JobX with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception
 */

private void shutdown() {

    String address = "localhost";

    Integer shutdownPort = Integer.valueOf(PropertiesLoader.getProperty(Constants.PARAM_JOBX_SHUTDOWN_KEY));

    // Stop the existing server
    try {
        Socket socket = new Socket(address, shutdownPort);
        OutputStream stream = socket.getOutputStream();
        for (int i = 0; i < shutdown.length(); i++) {
            stream.write(shutdown.charAt(i));
        }
        stream.flush();
        socket.close();
    } catch (Exception e) {
        if (logger.isErrorEnabled()) {
            logger.error("[JobX] Agent.stop error:{} ", e);
        }
        System.exit(1);
    }
}
 
Example 2
Source File: TcpClient.java    From xio with Apache License 2.0 6 votes vote down vote up
public static String sendReq(String host, int port, String req) {

    try {
      Socket clientSocket = new Socket(host, port);
      DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
      outToServer.writeBytes(req + '\n');

      BufferedReader inFromServer =
          new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      String response = inFromServer.readLine();
      clientSocket.close();

      return response;

    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
 
Example 3
Source File: StopListenerThread.java    From karate with MIT License 6 votes vote down vote up
@Override
public void run() {
    logger.info("starting thread: {}", getName());
    Socket accept;
    try {
        accept = socket.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        reader.readLine();
        logger.info("shutting down thread: {}", getName());
        stoppable.stop();
        accept.close();
        socket.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: RMIRefServer.java    From marshalsec with MIT License 6 votes vote down vote up
private void doMessage ( Socket s, DataInputStream in, DataOutputStream out ) throws Exception {
    System.err.println("Reading message...");

    int op = in.read();

    switch ( op ) {
    case TransportConstants.Call:
        // service incoming RMI call
        doCall(in, out);
        break;

    case TransportConstants.Ping:
        // send ack for ping
        out.writeByte(TransportConstants.PingAck);
        break;

    case TransportConstants.DGCAck:
        UID.read(in);
        break;

    default:
        throw new IOException("unknown transport op " + op);
    }

    s.close();
}
 
Example 5
Source File: ServerConnectionSource.java    From codeu_project_2017 with Apache License 2.0 6 votes vote down vote up
private static Connection fromSocket(final Socket socket) throws IOException {

    return new Connection() {

      @Override
      public InputStream in() throws IOException {
        return socket.getInputStream();
      }

      @Override
      public OutputStream out() throws IOException {
        return socket.getOutputStream();
      }

      @Override
      public void close() throws IOException {
        socket.close();
      }
    };
  }
 
Example 6
Source File: Wait.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
private static Callable<Boolean> portChecker(boolean freeCheck, int port) {
    return () -> {
        Socket socket = new Socket();
        socket.setSoTimeout(500);
        try {
            System.out.println("Trying to connect to port " + port);
            socket.connect(new InetSocketAddress(port), 500);
            socket.close();
            System.out.println("Was able to connect to port " + port);
            return !freeCheck;
        } catch (SocketTimeoutException | ConnectException ignored) {
            System.out.println("Was NOT able to connect to port " + port);
            return freeCheck;
        }
    };
}
 
Example 7
Source File: MissionDriver.java    From SoftwarePilot with MIT License 6 votes vote down vote up
byte[] readByte() throws IOException {
    ServerSocket ss = new ServerSocket(12013);
    System.out.println("Server: Waiting for Connection");
    Socket s = ss.accept();
    System.out.println("Server: Connection Reached");

    s = ss.accept();
    DataInputStream dIn = new DataInputStream(s.getInputStream());
    byte[] ret = new byte[0];
    //dIn.readInt();
    int length = dIn.readInt();
    System.out.println("Receiving "+length+" Bytes");
    if(length > 0) {
        ret = new byte[length];
        dIn.readFully(ret, 0, ret.length);
    }

    s.close();
    ss.close();
    return ret;
}
 
Example 8
Source File: TCPNetSyslogWriter.java    From syslog4j-graylog2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void closeSocket(Socket socketToClose) {
    if (socketToClose == null) {
        return;
    }

    try {
        socketToClose.close();

    } catch (IOException ioe) {
        if (!"Socket is closed".equalsIgnoreCase(ioe.getMessage())) {
            throw new SyslogRuntimeException(ioe);
        }

    } finally {
        if (socketToClose == this.socket) {
            this.socket = null;
        }
    }
}
 
Example 9
Source File: CassandraNodeImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public Long call() {
    Integer privatePort = entity.getThriftPort();
    if (privatePort == null) return -1L;
    
    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, privatePort);

    try {
        long start = System.currentTimeMillis();
        Socket s = new Socket(hp.getHostText(), hp.getPort());
        s.close();
        long latency = System.currentTimeMillis() - start;
        return latency;
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        if (log.isDebugEnabled())
            log.debug("Cassandra thrift port poll failure: "+e);
        return -1L;
    }
}
 
Example 10
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with MIT License 6 votes vote down vote up
@Test
public void testPinnedDomainSuccessLeaf() throws IOException {
    String serverHostname = "datatheorem.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection succeeds
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    Socket socket = test.createSocket(serverHostname, 443);
    socket.getInputStream();

    assertTrue(socket.isConnected());
    socket.close();

    // Ensure the background reporter was NOT called
    verify(mockReporter, never()).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
Example 11
Source File: SocketTextStreamFunctionTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSocketSourceSimpleOutput() throws Exception {
	ServerSocket server = new ServerSocket(0);
	Socket channel = null;

	try {
		SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), "\n", 0);

		SocketSourceThread runner = new SocketSourceThread(source, "test1", "check");
		runner.start();

		channel = server.accept();
		OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream());

		writer.write("test1\n");
		writer.write("check\n");
		writer.flush();
		runner.waitForNumElements(2);

		runner.cancel();
		runner.interrupt();

		runner.waitUntilDone();

		channel.close();
	}
	finally {
		if (channel != null) {
			IOUtils.closeQuietly(channel);
		}
		IOUtils.closeQuietly(server);
	}
}
 
Example 12
Source File: IoUtils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Closes 'socket', ignoring any exceptions. Does nothing if 'socket' is null.
 */
public static void closeQuietly(Socket socket) {
    if (socket != null) {
        try {
            socket.close();
        } catch (Exception ignored) {
        }
    }
}
 
Example 13
Source File: IOUtils.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Closes the socket ignoring {@link IOException}
 *
 * @param sock the Socket to close
 */
public static void closeSocket(Socket sock) {
  if (sock != null) {
    try {
      sock.close();
    } catch (IOException ignored) {
    }
  }
}
 
Example 14
Source File: VisionDriver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
void readFullPic() throws IOException {
    ServerSocket ss = new ServerSocket(12013);
    System.out.println("Server: Waiting for Connection");
    Socket s = ss.accept();
    System.out.println("Server: Connection Reached");

    String line, message = "";
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

    System.out.println("Reading Metadata");
    while((line = br.readLine())!= null) {
        if(!line.equals("over")) {
            System.out.println(line);
            message += line+"\n";
        } else {
            System.out.println("OVER");
            break;
        }
    }
    System.out.println("Metadata Done:");
    System.out.println(message);
    s.close();

    s = ss.accept();
    DataInputStream dIn = new DataInputStream(s.getInputStream());
    byte[] ret = new byte[0];

    int length = dIn.readInt();
    System.out.println("Receiving "+length+" Bytes");
    if(length > 0) {
        ret = new byte[length];
        dIn.readFully(ret, 0, ret.length);
    }

    System.out.println(message);
    s.close();
    ss.close();
    writeByte(ret);
    writeYaml(message);
}
 
Example 15
Source File: BalancedParentheses.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    ServerSocket serverSock = new ServerSocket(serverPort);

    // signal client, it's ready to accecpt connection
    serverPort = serverSock.getLocalPort();
    serverReady = true;

    // accept a connection
    Socket socket = serverSock.accept();
    System.out.println("Server: Connection accepted");

    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();

    // read the bindRequest
    while (is.read() != -1) {
        // ignore
        is.skip(is.available());
        break;
    }

    byte[] bindResponse = {0x30, 0x0C, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0A,
                           0x01, 0x00, 0x04, 0x00, 0x04, 0x00};
    // write bindResponse
    os.write(bindResponse);
    os.flush();

    // ignore any more request.
    while (is.read() != -1) {
        // ignore
        is.skip(is.available());
    }

    is.close();
    os.close();
    socket.close();
    serverSock.close();
}
 
Example 16
Source File: IOUtils.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
public static void closeQuietly(Socket closeable) {
    if (closeable == null)
        return;

    try {
        closeable.close();
    } catch (IOException e) {
        log.debug(e.getMessage());
    }
}
 
Example 17
Source File: BHttpConnectionBase.java    From java-android-websocket-client with Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown() throws IOException {
    final Socket socket = this.socketHolder.getAndSet(null);
    if (socket != null) {
        // force abortive close (RST)
        try {
            socket.setSoLinger(true, 0);
        } catch (final IOException ex) {
        } finally {
            socket.close();
        }
    }
}
 
Example 18
Source File: NonAutoClose.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
void doServerSide() throws Exception {
    if (VERBOSE) {
        System.out.println("Starting server");
    }

    /*
     * Setup the SSL stuff
     */
    SSLSocketFactory sslsf =
         (SSLSocketFactory) SSLSocketFactory.getDefault();

    ServerSocket serverSocket = new ServerSocket(SERVER_PORT);

    SERVER_PORT = serverSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    Socket plainSocket = serverSocket.accept();
    InputStream is = plainSocket.getInputStream();
    OutputStream os = plainSocket.getOutputStream();

    expectValue(is.read(), PLAIN_CLIENT_VAL, "Server");

    os.write(PLAIN_SERVER_VAL);
    os.flush();

    for (int i = 1; i <= NUM_ITERATIONS; i++) {
        if (VERBOSE) {
            System.out.println("=================================");
            System.out.println("Server Iteration #" + i);
        }

        SSLSocket ssls = (SSLSocket) sslsf.createSocket(plainSocket,
            SERVER_NAME, plainSocket.getPort(), false);

        ssls.setUseClientMode(false);
        InputStream sslis = ssls.getInputStream();
        OutputStream sslos = ssls.getOutputStream();

        expectValue(sslis.read(), TLS_CLIENT_VAL, "Server");

        sslos.write(TLS_SERVER_VAL);
        sslos.flush();

        sslis.close();
        sslos.close();
        ssls.close();

        if (VERBOSE) {
            System.out.println("TLS socket is closed");
        }
    }

    expectValue(is.read(), PLAIN_CLIENT_VAL, "Server");

    os.write(PLAIN_SERVER_VAL);
    os.flush();

    is.close();
    os.close();
    plainSocket.close();

    if (VERBOSE) {
        System.out.println("Server plain socket is closed");
    }
}
 
Example 19
Source File: SocketListener.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void run()
{
  ServerSocket socket = this.socket;
  Socket client = null;
  System.out.println("starting up");
  
  while (!done) {

    try {

      while (transactionManager.activeCount() >= httpConfig
          .getMaxConnections()) {
        try {
          Thread.sleep(50);
          if (done) {
            break;
          }
        } catch (final Exception e) {
        }
      }

      if (!done) {
        client = socket.accept();
        if (done) {
          client.close();
          break;
        }
      }
      
      transactionManager.startTransaction(client, httpConfig);

    } catch (final InterruptedIOException iioe) {
      if (!done && log.doDebug()) {
        log.debug("Communication error on "
                  + (host != null ? (host + ":") : "") + port, iioe);
      }
    } catch (final IOException ioe) {
      if (!done && log.doDebug()) {
        log.debug("Communication error on "
                  + (host != null ? (host + ":") : "") + port, ioe);
      }
    } catch (final ThreadDeath td) {
      throw td;
    } catch (final Throwable t) {
      if (!done && log.doDebug()) {
        log.debug("Internal error on" + (host != null ? (host + ":") : "")
                  + port, t);
      }
    }

  }

  try {
    if (socket != null) {
      socket.close();
    }
  } catch (final IOException ignore) {
  }
  socket = null;
}
 
Example 20
Source File: NioSocketChannelTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Reproduces the issue #1600
 */
@Test
public void testFlushCloseReentrance() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        final Queue<ChannelFuture> futures = new LinkedBlockingQueue<ChannelFuture>();

        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childOption(ChannelOption.SO_SNDBUF, 1024);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                // Write a large enough data so that it is split into two loops.
                futures.add(ctx.write(
                        ctx.alloc().buffer().writeZero(1048576)).addListener(ChannelFutureListener.CLOSE));
                futures.add(ctx.write(ctx.alloc().buffer().writeZero(1048576)));
                ctx.flush();
                futures.add(ctx.write(ctx.alloc().buffer().writeZero(1048576)));
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        InputStream in = s.getInputStream();
        byte[] buf = new byte[8192];
        for (;;) {
            if (in.read(buf) == -1) {
                break;
            }

            // Wait a little bit so that the write attempts are split into multiple flush attempts.
            Thread.sleep(10);
        }
        s.close();

        assertThat(futures.size(), is(3));
        ChannelFuture f1 = futures.poll();
        ChannelFuture f2 = futures.poll();
        ChannelFuture f3 = futures.poll();
        assertThat(f1.isSuccess(), is(true));
        assertThat(f2.isDone(), is(true));
        assertThat(f2.isSuccess(), is(false));
        assertThat(f2.cause(), is(instanceOf(ClosedChannelException.class)));
        assertThat(f3.isDone(), is(true));
        assertThat(f3.isSuccess(), is(false));
        assertThat(f3.cause(), is(instanceOf(ClosedChannelException.class)));
    } finally {
        group.shutdownGracefully().sync();
    }
}