java.net.Socket.close()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(8.6k)|赞(0)|评价(0)|浏览(256)

本文整理了Java中java.net.Socket.close()方法的一些代码示例,展示了Socket.close()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Socket.close()方法的具体详情如下:
包路径:java.net.Socket
类名称:Socket
方法名:close

Socket.close介绍

[英]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.
[中]关闭插座。此后无法重新连接或绑定到此套接字,这意味着必须创建一个新的套接字实例。

代码示例

代码示例来源: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);
      }
    }
  }
}

相关文章