Tabnine Logo
Socket.<init>
Code IndexAdd Tabnine to your IDE (free)

How to use
java.net.Socket
constructor

Best Java code snippets using java.net.Socket.<init> (Showing top 20 results out of 16,101)

Refine searchRefine arrow

  • Socket.getInputStream
  • Socket.getOutputStream
  • Socket.close
  • Socket.connect
  • InetSocketAddress.<init>
  • InputStreamReader.<init>
  • BufferedReader.<init>
  • PrintStream.println
origin: iluwatar/java-design-patterns

@Override
public void run() {
 try (Socket socket = new Socket(InetAddress.getLocalHost(), serverPort)) {
  OutputStream outputStream = socket.getOutputStream();
  PrintWriter writer = new PrintWriter(outputStream);
  sendLogRequests(writer, socket.getInputStream());
 } catch (IOException e) {
  LOGGER.error("error sending requests", e);
  throw new RuntimeException(e);
 }
}
origin: stackoverflow.com

 public static boolean pingHost(String host, int port, int timeout) {
  try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress(host, port), timeout);
    return true;
  } catch (IOException e) {
    return false; // Either timeout or unreachable or failed DNS lookup.
  }
}
origin: apache/incubator-druid

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

/**
 * 激活网络
 */
private Socket connect(InetSocketAddress address) throws IOException {
  final Socket socket = new Socket();
  socket.setSoTimeout(0);
  socket.connect(address, _1MIN);
  socket.setKeepAlive(true);
  socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
  socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  return socket;
}
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);
      }
    }
  }
}
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: 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: stackoverflow.com

 try {
  Socket x = new Socket("1.1.1.1", 6789);
  x.getInputStream().read()
} catch (IOException e) {
  System.err.println("Connection could not be established, please try again later!")
}
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: apache/flink

private void createConnection() throws IOException {
  client = new Socket(hostName, port);
  client.setKeepAlive(true);
  client.setTcpNoDelay(true);
  outputStream = client.getOutputStream();
}
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: apache/zookeeper

public static void dump(String host, int port) {
  Socket s = null;
  try {
    byte[] reqBytes = new byte[4];
    ByteBuffer req = ByteBuffer.wrap(reqBytes);
    req.putInt(ByteBuffer.wrap("dump".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[1024];
    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);
      }
    }
  }
}
origin: stackoverflow.com

 public static Future<Boolean> portIsOpen(final ExecutorService es, final String ip, final int port, final int timeout) {
 return es.submit(new Callable<Boolean>() {
   @Override public Boolean call() {
    try {
     Socket socket = new Socket();
     socket.connect(new InetSocketAddress(ip, port), timeout);
     socket.close();
     return true;
    } catch (Exception ex) {
     return false;
    }
   }
  });
}
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: prestodb/presto

  private static boolean isPortOpen(String host, Integer port)
  {
    try (Socket socket = new Socket()) {
      socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), 1000);
      return true;
    }
    catch (ConnectException | SocketTimeoutException e) {
      return false;
    }
    catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
}
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: jMonkeyEngine/jmonkeyengine

public SocketConnector( InetAddress address, int port ) throws IOException
{
  this.sock = new Socket(address, port);
  remoteAddress = sock.getRemoteSocketAddress(); // for info purposes 
  
  // Disable Nagle's buffering so data goes out when we
  // put it there.
  sock.setTcpNoDelay(true);
  
  in = sock.getInputStream();
  out = sock.getOutputStream();
  
  connected.set(true);
}
origin: apache/storm

@Override
public void prepare(Map<String, Object> topoConf, Object registrationArgument, TopologyContext context, IErrorReporter errorReporter) {
  String[] parts = ((String) registrationArgument).split(":", 2);
  host = parts[0];
  port = Integer.valueOf(parts[1]);
  try {
    socket = new Socket(host, port);
    out = socket.getOutputStream();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
origin: pentaho/pentaho-kettle

private static int getUnusedPort() throws IOException {
 Socket s = new Socket();
 s.bind( (SocketAddress) null );
 int var1;
 try {
  var1 = s.getLocalPort();
 } finally {
  s.close();
 }
 return var1;
}
origin: apache/storm

@Override
public void open(Map<String, Object> conf, TopologyContext context, SpoutOutputCollector collector) {
  this.collector = collector;
  this.queue = new LinkedBlockingDeque<>();
  this.emitted = new HashMap<>();
  this.objectMapper = new ObjectMapper();
  try {
    socket = new Socket(host, port);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  } catch (IOException e) {
    throw new RuntimeException("Error opening socket: host " + host + " port " + port);
  }
  readerThread = new Thread(new SocketSpout.SocketReaderRunnable());
  readerThread.start();
}
java.netSocket<init>

Javadoc

Creates a new unconnected socket. When a SocketImplFactory is defined it creates the internal socket implementation, otherwise the default socket implementation will be used for this socket.

Popular methods of Socket

  • close
    Closes the socket. It is not possible to reconnect or rebind to this socket thereafter which means a
  • 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

  • Start an intent from android
  • addToBackStack (FragmentTransaction)
  • findViewById (Activity)
  • runOnUiThread (Activity)
  • Container (java.awt)
    A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT co
  • Path (java.nio.file)
  • SQLException (java.sql)
    An exception that indicates a failed JDBC operation. It provides the following information about pro
  • HashMap (java.util)
    HashMap is an implementation of Map. All optional operations are supported.All elements are permitte
  • TimeUnit (java.util.concurrent)
    A TimeUnit represents time durations at a given unit of granularity and provides utility methods to
  • Response (javax.ws.rs.core)
    Defines the contract between a returned instance and the runtime when an application needs to provid
  • From CI to AI: The AI layer in your organization
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