Tabnine Logo
Socket.close
Code IndexAdd Tabnine to your IDE (free)

How to use
close
method
in
java.net.Socket

Best Java code snippets using java.net.Socket.close (Showing top 20 results out of 16,920)

Refine searchRefine arrow

  • Socket.getInputStream
  • Socket.getOutputStream
  • Socket.<init>
  • InputStreamReader.<init>
  • PrintStream.println
  • BufferedReader.<init>
origin: apache/incubator-druid

@VisibleForTesting
protected void checkConnection(String host, int port) throws IOException
{
 new Socket(host, port).close();
}
origin: jenkinsci/jenkins

@Override
public void handle(Socket socket) throws IOException, InterruptedException {
  try {
    try (OutputStream stream = socket.getOutputStream()) {
      LOGGER.log(Level.FINE, "Received ping request from {0}", socket.getRemoteSocketAddress());
      stream.write(ping);
      stream.flush();
      LOGGER.log(Level.FINE, "Sent ping response to {0}", socket.getRemoteSocketAddress());
    }
  } finally {
    socket.close();
  }
}
origin: stanfordnlp/CoreNLP

/**
 * Tell the server to exit
 */
public void sendQuit() 
 throws IOException
{
 Socket socket = new Socket(host, port);
 
 Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
 out.write("quit\n");
 out.flush();    
 socket.close();
}
origin: Netflix/eureka

  private void processRequest(final Socket s) {
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String line = rd.readLine();
      if (line != null) {
        System.out.println("Received a request from the example client: " + line);
      }
      String response = "BAR " + new Date();
      System.out.println("Sending the response to the client: " + response);

      PrintStream out = new PrintStream(s.getOutputStream());
      out.println(response);

    } catch (Throwable e) {
      System.err.println("Error processing requests");
    } finally {
      if (s != null) {
        try {
          s.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
origin: thinkaurelius/titan

  public static void main(String args[]) {
    if (2 != args.length) {
      System.err.println(MSG_USAGE);
      System.exit(E_USAGE);
    }
    try {
      Socket s = new Socket(
        InetAddress.getByName(args[0]),
        Integer.valueOf(args[1]).intValue());
      s.close();
      System.exit(0);
    } catch (Throwable t) {
      System.err.println(t.toString());
      System.exit(E_FAILED);
    }
  }
}
origin: cmusphinx/sphinx4

/** Closes the socket connection */
public synchronized void close() {
  try {
    if (socket != null) {
      socket.close();
    } else {
      System.err.println("SocketCommandClient.close(): " +
          "socket is null");
    }
  } catch (IOException ioe) {
    System.err.println("Trouble closing socket");
  }
  socket = null;
}
origin: stackoverflow.com

  serverSocket = new ServerSocket(4444);
} catch (IOException ex) {
  System.out.println("Can't setup server on this port number. ");
  socket = serverSocket.accept();
} catch (IOException ex) {
  System.out.println("Can't accept client connection. ");
  in = socket.getInputStream();
} catch (IOException ex) {
  System.out.println("Can't get socket input stream. ");
socket.close();
serverSocket.close();
origin: frohoff/ysoserial

DataOutputStream dos = null;
try {
  System.err.println("* Opening JRMP socket " + isa);
  s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort());
  s.setKeepAlive(true);
  s.setTcpNoDelay(true);
  OutputStream os = s.getOutputStream();
  dos = new DataOutputStream(os);
    s.close();
origin: jenkinsci/jenkins

  public boolean connect(Socket socket) throws IOException {
    try {
      LOGGER.log(Level.FINE, "Requesting ping from {0}", socket.getRemoteSocketAddress());
      try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
        out.writeUTF("Protocol:Ping");
        try (InputStream in = socket.getInputStream()) {
          byte[] response = new byte[ping.length];
          int responseLength = in.read(response);
          if (responseLength == ping.length && Arrays.equals(response, ping)) {
            LOGGER.log(Level.FINE, "Received ping response from {0}", socket.getRemoteSocketAddress());
            return true;
          } else {
            LOGGER.log(Level.FINE, "Expected ping response from {0} of {1} got {2}", new Object[]{
                socket.getRemoteSocketAddress(),
                new String(ping, "UTF-8"),
                responseLength > 0 && responseLength <= response.length ?
                  new String(response, 0, responseLength, "UTF-8") :
                  "bad response length " + responseLength
            });
            return false;
          }
        }
      }
    } finally {
      socket.close();
    }
  }
}
origin: stackoverflow.com

 public void gracefulDisconnect(Socket sok) {
  InputStream is = sok.getInputStream();
  sok.shutdownOutput(); // Sends the 'FIN' on the network
  while (is.read() >= 0) ; // "read()" returns '-1' when the 'FIN' is reached
  sok.close(); // Now we can close the Socket
}
origin: stanfordnlp/CoreNLP

/**
 * Returs a Tree from the server connected to at host:port.
 */
public Tree getTree(String query) 
 throws IOException
{
 Socket socket = new Socket(host, port);
 Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
 out.write("tree " + query + "\n");
 out.flush();
 ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
 Object o;
 try {
  o = ois.readObject();
 } catch (ClassNotFoundException e) {
  throw new RuntimeException(e);
 }
 if (!(o instanceof Tree)) {
  throw new IllegalArgumentException("Expected a tree");
 }
 Tree tree = (Tree) o;
 socket.close();
 return tree;
}
origin: stackoverflow.com

 // output on my machine: "192.168.1.102"
Socket s = new Socket("192.168.1.1", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();

// output on my machine: "127.0.1.1"
System.out.println(InetAddress.getLocalHost().getHostAddress());
origin: stackoverflow.com

 public class MyServer {
  public static final int PORT = 12345;
  public static void main(String[] args) throws IOException, InterruptedException {
    ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
    Socket s = ss.accept();
    Thread.sleep(5000);
    ss.close();
    s.close();
  }
}

public class MyClient {
  public static void main(String[] args) throws IOException, InterruptedException {
    Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
    System.out.println(" connected: " + s.isConnected());
    Thread.sleep(10000);
    System.out.println(" connected: " + s.isConnected());
  }
}
origin: org.apache.logging.log4j/log4j-core

@Override
public void run() {
  System.out.println("TCP Server started");
  this.thread = Thread.currentThread();
  while (!shutdown) {
        socket = sock.accept();
        socket.setSoLinger(true, 0);
        final InputStream in = socket.getInputStream();
        int i = in.read(buffer, 0, buffer.length);
        while (i != -1) {
            i = in.read(buffer, 0, buffer.length);
          } else if (i == 0) {
            System.out.println("No data received");
          } else {
            System.out.println("Message too long");
      } finally {
        if (socket != null) {
          socket.close();
origin: jenkinsci/jenkins

  Writer o = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
  InputStream i = s.getInputStream();
  IOUtils.copy(i, new NullOutputStream());
  s.shutdownInput();
} finally {
  s.close();
origin: stanfordnlp/CoreNLP

/**
 * Tokenize the text according to the parser's tokenizer, 
 * return it as whitespace tokenized text.
 */
public String getTokenizedText(String query) 
 throws IOException
{
 Socket socket = new Socket(host, port);
 Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
 out.write("tokenize " + query + "\n");
 out.flush();
 String result = readResult(socket);
 socket.close();
 return result;
}
origin: mpusher/mpush

public static boolean checkHealth(String ip, int port) {
  try {
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(ip, port), 1000);
    socket.close();
    return true;
  } catch (IOException e) {
    return false;
  }
}
origin: stackoverflow.com

 String msg_received;

ServerSocket socket = new ServerSocket(1755);
Socket clientSocket = socket.accept();       //This is blocking. It will wait.
DataInputStream DIS = new DataInputStream(clientSocket.getInputStream());
msg_received = DIS.readUTF();
clientSocket.close();
socket.close();
origin: apache/geode

private void rejectUnknownProtocolConnection(Socket socket, int gossipVersion) {
 try {
  socket.getOutputStream().write("unknown protocol version".getBytes());
  socket.getOutputStream().flush();
  socket.close();
 } catch (IOException e) {
  log.debug("exception in sending reply to process using unknown protocol " + gossipVersion, e);
 }
}
origin: apache/zookeeper

public static void kill(String host, int port) {
  Socket s = null;
  try {
    byte[] reqBytes = new byte[4];
    ByteBuffer req = ByteBuffer.wrap(reqBytes);
    req.putInt(ByteBuffer.wrap("kill".getBytes()).getInt());
    s = new Socket();
    s.setSoLinger(false, 10);
    s.setSoTimeout(20000);
    s.connect(new InetSocketAddress(host, port));
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    os.write(reqBytes);
    byte[] resBytes = new byte[4];
    int rc = is.read(resBytes);
    String retv = new String(resBytes);
    System.out.println("rc=" + rc + " retv=" + retv);
  } catch (IOException e) {
    LOG.warn("Unexpected exception", e);
  } finally {
    if (s != null) {
      try {
        s.close();
      } catch (IOException e) {
        LOG.warn("Unexpected exception", e);
      }
    }
  }
}
java.netSocketclose

Javadoc

Closes the socket. It is not possible to reconnect or rebind to this socket thereafter which means a new socket instance has to be created.

Popular methods of Socket

  • <init>
    Creates an unconnected socket with the given socket implementation.
  • getOutputStream
    Returns an output stream to write data into this socket.
  • getInputStream
    Returns an input stream to read data from this socket.
  • connect
    Connects this socket to the given remote host address and port specified by the SocketAddress remote
  • setSoTimeout
    Sets this socket's SocketOptions#SO_TIMEOUT in milliseconds. Use 0 for no timeout. To take effect, t
  • getInetAddress
    Returns the IP address of the target host this socket is connected to, or null if this socket is not
  • setTcpNoDelay
    Sets this socket's SocketOptions#TCP_NODELAY option.
  • getPort
    Returns the port number of the target host this socket is connected to, or 0 if this socket is not y
  • isClosed
    Returns whether this socket is closed.
  • getRemoteSocketAddress
    Returns the remote address and port of this socket as a SocketAddress or null if the socket is not c
  • setKeepAlive
    Sets this socket's SocketOptions#SO_KEEPALIVE option.
  • isConnected
    Returns whether this socket is connected to a remote host.
  • setKeepAlive,
  • isConnected,
  • bind,
  • setSoLinger,
  • setSendBufferSize,
  • setReceiveBufferSize,
  • getLocalAddress,
  • getLocalPort,
  • shutdownOutput

Popular in Java

  • Reactive rest calls using spring rest template
  • getContentResolver (Context)
  • getExternalFilesDir (Context)
  • putExtra (Intent)
  • ObjectMapper (com.fasterxml.jackson.databind)
    ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Pl
  • MessageDigest (java.security)
    Uses a one-way hash function to turn an arbitrary number of bytes into a fixed-length byte sequence.
  • Comparator (java.util)
    A Comparator is used to compare two objects to determine their ordering with respect to each other.
  • NoSuchElementException (java.util)
    Thrown when trying to retrieve an element past the end of an Enumeration or Iterator.
  • TreeSet (java.util)
    TreeSet is an implementation of SortedSet. All optional operations (adding and removing) are support
  • JList (javax.swing)
  • Top plugins for WebStorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now