Java examples for Network:Socket
Creating a Client Socket
import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class Main { public static void main(String[] args) { // Create a socket without a timeout try {/*from www . j a v a2 s . c o m*/ InetAddress addr = InetAddress.getByName("java.sun.com"); int port = 80; // This constructor will block until the connection succeeds Socket socket = new Socket(addr, port); } catch (UnknownHostException e) { } catch (IOException e) { } } }
import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.net.UnknownHostException; public class Main { public static void main(String[] args) { // Create a socket with a timeout try {/*from w w w . ja v a 2 s . co m*/ InetAddress addr = InetAddress.getByName("java.sun.com"); int port = 80; SocketAddress sockaddr = new InetSocketAddress(addr, port); // Create an unbound socket Socket sock = new Socket(); // This method will block no more than timeoutMs. // If the timeout occurs, SocketTimeoutException is thrown. int timeoutMs = 2000; // 2 seconds sock.connect(sockaddr, timeoutMs); } catch (UnknownHostException e) { } catch (SocketTimeoutException e) { } catch (IOException e) { } } }