import java.net.Socket; import java.net.SocketAddress; import java.net.InetSocketAddress; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.BufferedReader; class Demo { // Helper function private static void closeAll(Socket socket, OutputStream out, BufferedReader in) { try { if (out != null) out.close(); if (in != null) in.close(); if (socket != null) socket.close(); // Close the socket last } catch (Exception ex) { } } static boolean socketDialog(final String host, final int port, final int timeoutSeconds, final String sendthis) { Socket socket = null; OutputStream os = null; BufferedReader in = null; try { socket = new Socket(); final SocketAddress addr = new InetSocketAddress(host, port); socket.connect(addr, timeoutSeconds * 1000); os = socket.getOutputStream(); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Send what you want os.write(sendthis.getBytes()); // Now, get the reply String line; while ((line = in.readLine()) != null) { System.out.println("reply: " + line); } closeAll(socket, os, in); } catch (Exception ex) { closeAll(socket, os, in); System.out.println("socketDialog problem " + ex.toString()); return false; } return true; } public static void main(String[] args) { // This actually fetch the example.com home page socketDialog("example.com", 80, 15, "GET /\r\n\r\n"); } }
Programming Tips - Java: Two-way communication on a socket in Java With a timeout
Date: 2013mar28
Updateed: 2025sep16
Language: Java
Keywords: TCP/IP
Q. Java: Two-way communication on a socket in Java With a timeout
A. Use Java's Socket class as show in this full working demo: