import java.net.Socket; Socket socket = new Socket("example.com", 80); socket.setSoTimeout(5000); // set a 5 second timeout
import java.net.Socket; Socket socket = new Socket("example.com", 80); socket.setSoTimeout(10000); // set a 10 second timeout try { // send a request to the server and wait for a response byte[] request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n".getBytes(); socket.getOutputStream().write(request); byte[] buffer = new byte[1024]; int bytesRead = socket.getInputStream().read(buffer); // do something with the response } catch (SocketTimeoutException e) { // handle timeout }This sets a 10 second timeout on a socket that is connecting to the website example.com on port 80, and then sends a GET request to the server. If the server does not respond within 10 seconds, a SocketTimeoutException is thrown, which can be caught and handled. The java.net package library contains classes and interfaces for networking, including sockets, URLs, and protocols.