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

The following are Jave code examples for showing how to use close() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: DefaultClientConnection.java   View Source Code Vote up 6 votes
/**
 * Force-closes this connection.
 * If the connection is still in the process of being open (the method
 * {@link #opening opening} was already called but
 * {@link #openCompleted openCompleted} was not), the associated
 * socket that is being connected to a remote address will be closed.
 * That will interrupt a thread that is blocked on connecting
 * the socket.
 * If the connection is not yet open, this will prevent the connection
 * from being opened.
 *
 * @throws IOException      in case of a problem
 */
@Override
public void shutdown() throws IOException {
    shutdown = true;
    try {
        super.shutdown();
        if (log.isDebugEnabled()) {
            log.debug("Connection " + this + " shut down");
        }
        Socket sock = this.socket; // copy volatile attribute
        if (sock != null)
            sock.close();
    } catch (IOException ex) {
        log.debug("I/O error shutting down connection", ex);
    }
}
 
Example 2
Project: openjdk-jdk10   File: SetReceiveBufferSize.java   View Source Code Vote up 6 votes
public SetReceiveBufferSize() throws Exception {
    ServerSocket ss = new ServerSocket(0);
    Socket s = new Socket("localhost", ss.getLocalPort());
    Socket accepted = ss.accept();
    try {
        s.setReceiveBufferSize(0);
    } catch (IllegalArgumentException e) {
        return;
    } catch (Exception ex) {
    } finally {
        ss.close();
        s.close();
        accepted.close();
    }
    throw new RuntimeException("IllegalArgumentException not thrown!");
}
 
Example 3
Project: flume-release-1.7.0   File: TestNetcatSource.java   View Source Code Vote up 6 votes
/**
 * Test that line above MaxLineLength are discarded
 *
 * @throws InterruptedException
 * @throws IOException
 */
@Test
public void testMaxLineLength() throws InterruptedException, IOException {
  String encoding = "UTF-8";
  startSource(encoding, "false", "1", "10");
  Socket netcatSocket = new Socket(localhost, selectedPort);
  try {
    sendEvent(netcatSocket, "123456789", encoding);
    Assert.assertArrayEquals("Channel contained our event",
                             "123456789".getBytes(defaultCharset), getFlumeEvent());
    sendEvent(netcatSocket, english, encoding);
    Assert.assertEquals("Channel does not contain an event", null, getRawFlumeEvent());
  } finally {
    netcatSocket.close();
    stopSource();
  }
}
 
Example 4
Project: hadoop   File: TestNetUtils.java   View Source Code Vote up 6 votes
/**
 * Test that we can't accidentally connect back to the connecting socket due
 * to a quirk in the TCP spec.
 *
 * This is a regression test for HADOOP-6722.
 */
@Test
public void testAvoidLoopbackTcpSockets() throws Exception {
  Configuration conf = new Configuration();

  Socket socket = NetUtils.getDefaultSocketFactory(conf)
    .createSocket();
  socket.bind(new InetSocketAddress("127.0.0.1", 0));
  System.err.println("local address: " + socket.getLocalAddress());
  System.err.println("local port: " + socket.getLocalPort());
  try {
    NetUtils.connect(socket,
      new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()),
      20000);
    socket.close();
    fail("Should not have connected");
  } catch (ConnectException ce) {
    System.err.println("Got exception: " + ce);
    assertTrue(ce.getMessage().contains("resulted in a loopback"));
  } catch (SocketException se) {
    // Some TCP stacks will actually throw their own Invalid argument exception
    // here. This is also OK.
    assertTrue(se.getMessage().contains("Invalid argument"));
  }
}
 
Example 5
Project: TensorFlowDetector-App   File: MainActivity.java   View Source Code Vote up 6 votes
private void checkForTrigger() {
    String msg_received;
    while(true){
        try{
            ServerSocket socket=new ServerSocket(serverPort);
            Socket clientSocket=socket.accept();
            DataInputStream DIS = new DataInputStream(clientSocket.getInputStream());
            msg_received = DIS.readUTF();
            clientSocket.close();
            socket.close();
        }
        catch(IOException e){
            msg_received=e.toString();
        }
        if(msg_received.equals("transmit_data")){

            Log.d("harsimarSingh","triggered");
            cameraView.captureImage();
        }}
}
 
Example 6
Project: tomcat7   File: JIoEndpoint.java   View Source Code Vote up 5 votes
private void closeSocket(Socket socket) {
    try {
        socket.close();
    } catch (IOException e) {
        // Ignore
    }
}
 
Example 7
Project: graphouse   File: MetricServer.java   View Source Code Vote up 5 votes
private void read() throws IOException {
    metrics.clear();
    Socket socket = serverSocket.accept();
    try {
        socket.setSoTimeout(socketTimeoutMillis);
        socket.setKeepAlive(false);
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            int updatedSeconds = (int) (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
            Metric metric = metricFactory.createMetric(line, updatedSeconds);
            if (metric != null) {
                metrics.add(metric);
                if (metrics.size() >= readBatchSize) {
                    metricCacher.submitMetrics(metrics);
                    metrics.clear();
                }
            }
        }
    } catch (SocketTimeoutException e) {
        log.warn("Socket timeout from " + socket.getRemoteSocketAddress().toString());
    } finally {
        socket.close();
    }
    metricCacher.submitMetrics(metrics);
    metrics.clear();
}
 
Example 8
Project: convertigo-eclipse   File: HttpProxyWorker.java   View Source Code Vote up 5 votes
private void closeSocket(Socket sock) {
   try {
      sock.close();
   }
   catch (Exception e) {
      // we cannot do anything if this op crashes
   }
}
 
Example 9
Project: aos-MediaLib   File: XMLRPCServer.java   View Source Code Vote up 5 votes
public void respond(Socket socket, Object[] params) throws IOException {

		String content = methodResponse(params);
		String response = RESPONSE + (content.length()) + NEWLINES + content;
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write(response.getBytes());
		outputStream.flush();
		outputStream.close();
		socket.close();
		Log.d(Tag.LOG, "response:" + response);
	}
 
Example 10
Project: vase   File: NotSupport.java   View Source Code Vote up 5 votes
@Override
public void process(Config config, String stateLine, Socket socket) {
    try {
        socket.close();
    } catch (Exception e) {
    }
}
 
Example 11
Project: jdk8u-jdk   File: ShutdownSimpleApplication.java   View Source Code Vote up 5 votes
public static void main(String args[]) throws Exception {

        if (args.length != 1) {
            throw new RuntimeException("Usage: ShutdownSimpleApplication" +
                " port-file");
        }

        // read the (TCP) port number from the given file

        File f = new File(args[0]);
        FileInputStream fis = new FileInputStream(f);
        byte b[] = new byte[8];
        int n = fis.read(b);
        if (n < 1) {
            throw new RuntimeException("Empty port-file");
        }
        fis.close();

        String str = new String(b, 0, n, "UTF-8");
        System.out.println("INFO: Port number of SimpleApplication: " + str);
        int port = Integer.parseInt(str);

        // Now connect to the port (which will shutdown application)

        System.out.println("INFO: Connecting to port " + port +
            " to shutdown SimpleApplication ...");
        System.out.flush();

        Socket s = new Socket();
        s.connect( new InetSocketAddress(port) );
        s.close();

        System.out.println("INFO: done connecting to SimpleApplication.");
        System.out.flush();

        System.exit(0);
    }
 
Example 12
Project: Nird2   File: TorPlugin.java   View Source Code Vote up 5 votes
private void tryToClose(@Nullable Socket s) {
	try {
		if (s != null) s.close();
	} catch (IOException e) {
		if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
	}
}
 
Example 13
Project: trading4j   File: OioServer.java   View Source Code Vote up 5 votes
private void handleClientInitialisationError(final Socket clientSocket, final IOException e) {
    final String addr = clientSocket.getRemoteSocketAddress().toString();
    admin.unexpectedEvent(String.format(
            "Can't initialize connection of client '%s' correctly. Closing the connection to it.", addr), e);
    try {
        clientSocket.close();
    } catch (IOException e1) {
        admin.unexpectedEvent(String.format("Could not close the connection to the client '%s'.", addr), e1);
    }

}
 
Example 14
Project: Nird2   File: LanTcpPluginTest.java   View Source Code Vote up 5 votes
@Test
public void testIncomingConnection() throws Exception {
	if (!systemHasLocalIpv4Address()) {
		System.err.println("WARNING: Skipping test, no local IPv4 address");
		return;
	}
	Callback callback = new Callback();
	Executor executor = Executors.newCachedThreadPool();
	DuplexPlugin plugin = new LanTcpPlugin(executor, backoff, callback,
			0, 0);
	plugin.start();
	// The plugin should have bound a socket and stored the port number
	assertTrue(callback.propertiesLatch.await(5, SECONDS));
	String ipPorts = callback.local.get("ipPorts");
	assertNotNull(ipPorts);
	String[] split = ipPorts.split(",");
	assertEquals(1, split.length);
	split = split[0].split(":");
	assertEquals(2, split.length);
	String addrString = split[0], portString = split[1];
	InetAddress addr = InetAddress.getByName(addrString);
	assertTrue(addr instanceof Inet4Address);
	assertFalse(addr.isLoopbackAddress());
	assertTrue(addr.isLinkLocalAddress() || addr.isSiteLocalAddress());
	int port = Integer.parseInt(portString);
	assertTrue(port > 0 && port < 65536);
	// The plugin should be listening on the port
	InetSocketAddress socketAddr = new InetSocketAddress(addr, port);
	Socket s = new Socket();
	s.connect(socketAddr, 100);
	assertTrue(callback.connectionsLatch.await(5, SECONDS));
	s.close();
	// Stop the plugin
	plugin.stop();
}
 
Example 15
Project: hadoop   File: IOUtils.java   View Source Code Vote up 5 votes
/**
 * 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 16
Project: AndroidDvbDriver   File: TransferThread.java   View Source Code Vote up 5 votes
private void quietClose(Socket s) {
    if (s != null) {
        try {
            s.close();
        } catch (IOException e) {
            if (lastException == null) lastException = e;
        }
    }
}
 
Example 17
Project: myster   File: ConnectionManager.java   View Source Code Vote up 5 votes
/**
 * Closes the socket ignoring any complaining.
 * 
 * @param socket
 */
private static void close(Socket socket) {
    try {
        socket.close();
    } catch (Exception ex) {
    }
}
 
Example 18
Project: LanChatLite   File: ReceiveFileThread.java   View Source Code Vote up 4 votes
/**
 * thread run method
 */
public void run() {
	
	System.out.println("[ReceiveFileThread] :: started on port " + port + "file size : " + fileSize);
       int progress = 0;
	try {
		
		ServerSocket ssock = new ServerSocket(port);			
		Socket socket = ssock.accept();
		int size = 10000;
		byte[] contents = new byte[size];

		//Initialize the FileOutputStream to the output file's full path.
		FileOutputStream fos = new FileOutputStream(filePath);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		InputStream is = socket.getInputStream();

		//No of bytes read in one read() call
		int bytesRead = 0; 
       
		//receiving file Message dialog window
		JFrame recFileMessFrame =  new JFrame("Recieving File");
		recFileMessFrame.setBounds(500, 300, 350, 200);
	  			
	  	JPanel panel = new JPanel();
	  	panel.setLayout(new GridLayout(9, 1));
	  	
	 	//progress bar for recieved data
	  	JProgressBar progressbar = new JProgressBar(0, 100); 	
	  	progressbar.setSize(new Dimension(100, 15));
	    progressbar.setBackground(Color.white);
	    progressbar.setForeground(Color.gray);		    
	   
	    //adding blank frame
	    for(int i = 0; i <= 2; i++){
		    panel.add(new JPanel());
		}
	    
	    JPanel progressPanel = new JPanel(new BorderLayout(5, 5));
		JLabel progressLabel = new JLabel();
		
		//adding progress label to progress panel
		progressPanel.add(progressLabel);			
		panel.add(progressPanel);
		
	    //adding progress panel to main panel
		panel.add(progressbar);
	
		recFileMessFrame.add(panel);
		recFileMessFrame.setVisible(true);
		long recFileSize = 0;
		
	    while((bytesRead=is.read(contents))!=-1){
	    			   	
	    	recFileSize += bytesRead; 
	    	//change the progressbar value
			progressbar.setValue((progress = (int)((recFileSize*100)/fileSize)));
			progressLabel.setText("File Recieved......." + progress + "%");		
			bos.write(contents, 0, bytesRead);
		}
		bos.flush();
		recFileMessFrame.setVisible(false);
		JOptionPane.showMessageDialog(null, "File recieved ! " + Paths.get(filePath).getFileName() );
		socket.close();
		ssock.close();
	} catch(Exception e) {
		System.out.println("[ReceiveFileThread] exception :: " + e);
		e.printStackTrace();
	}

	System.out.println("[ReceiveFileThread] :: File saved successfully!");
}
 
Example 19
Project: openjdk-jdk10   File: NonAutoClose.java   View Source Code Vote up 4 votes
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 20
Project: T0rlib4Android   File: Utilities.java   View Source Code Vote up 4 votes
public static Socket socks5rawSocketConnection(String networkHost, int networkPort, String socksHost, int socksPort)
        throws IOException {

    int bytesRead = 0;
    boolean end = false;
    String messageString = "";
    final byte[] messageByte = new byte[1000];

    Socket socket = new Socket();
    socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
    SocketAddress socksAddress = new InetSocketAddress(socksHost, socksPort);
    socket.connect(socksAddress, CONNECT_TIMEOUT_MILLISECONDS);

    DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
    outputStream.write((byte) 0x05);
    outputStream.write((byte) 0x01);
    outputStream.write((byte) 0x00);
    outputStream.write((byte) 0x01);
    outputStream.write(networkHost.getBytes());
    outputStream.writeShort((short) networkPort);

    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
    messageByte[0] = inputStream.readByte();
    messageByte[1] = inputStream.readByte();
    if (messageByte[0] != (byte) 0x05 || messageByte[1] != (byte) 0x00) {
        socket.close();
        throw new IOException("SOCKS4a connect failed, got " + messageByte[0] + " - " + messageByte[1] +
                ", but expected 0x00 - 0x5a");
    }

    ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

    int bytesToRead = byteBuffer.getShort();
    LOG.info("About to read " + bytesToRead + " octets");

    while (!end) {
        bytesRead = inputStream.read(messageByte);
        messageString += new String(messageByte, 0, bytesRead);
        if (messageString.length() == bytesToRead) {
            end = true;
        }
    }

    return socket;

}