Prepared by: Eng/ Basma Elshoky
Section 3: Socket
                                 Part I: socket for clients
   Java sockets are essential for network communication, acting as endpoints for
   sending and receiving data. A socket is created on a client device and attempts to
   connect to a server socket at a specified IP address and port number. Java programs
   normally use client sockets in the following fashion:
   • The program creates a new socket with a constructor.
   • The socket attempts to connect to the remote host.
   Socket class: Socket class represents a client-side socket, used to establish
   connections to a server. Constructors & Methods:
Constructor                            Description
Socket()                               Creates an unconnected socket.
Socket(String host, int port)          Creates a socket and connects it to the specified remote
                                       host on the specified port.
    Prepared by: Eng/ Basma Elshoky
Socket(String host, int port,         Creates a socket and connects it to the specified remote
InetAddress localAddr, int            host on the specified port, using the specified local address
localPort)                            and port to bind the socket.
Socket(InetAddress address, int       Creates a socket and connects it to the specified remote
port)                                 address on the specified port.
Socket(InetAddress address, int       Creates a socket and connects it to the specified remote
port, InetAddress localAddr, int      address on the specified port, using the specified local
localPort)                            address and port to bind the socket.
Method                                Description
connect(SocketAddress endpoint)       Connects this socket to the server with the specified
                                      address and port number.
close():                              Closes the socket.
getInputStream()                      Returns an input stream for this socket.
getOutputStream()                     Returns an output stream for this socket.
getInetAddress()                      Returns the remote address to which this socket is
                                      connected.
getLocalAddress():                    Returns the local address to which this socket is bound.
getPort()                             Returns the remote port to which this socket is connected.
getLocalPort()                        Returns the local port to which this socket is bound.
setSoTimeout(int timeout)             Sets the timeout in milliseconds for blocking socket
operations.                           operations.
getSoTimeout()                        Returns the timeout in milliseconds for blocking socket
                                      operations.
isClosed()                            Returns true if the socket has been closed.
isConnected()                         Returns true if the socket is connected to a remote host.
isBound()                             Returns true if the socket is bound to a local address and
                                      port.
getChannel()                          Returns the socket's SocketChannel if available.
Prepared by: Eng/ Basma Elshoky
Example 1: retrieve data programmatically using sockets (website on port 13).
import java.io.*;
import java.net.*;
import java.util.*;
public class App {
    public static void main(String[] args) throws Exception {
// String hostname = "localhost"; //java.net.ConnectException: Connection
refused: connect
        String hostname = "https://translate.google.com.eg/";
        Socket socket = null;
        try {
        socket = new Socket(hostname, 13);
        // read from the socket...
        }
        catch (IOException ex) {
            System.out.println("Error2:");
            System.err.println(ex);
        }
        finally {
        if (socket != null) {
        try {
        socket.close();
        }
        catch (IOException ex) {
            System.out.println("Error2:");
            System.err.println(ex);}
    }
   }
Prepared by: Eng/ Basma Elshoky
Lab 1: Check a connection with a website then apply some methods.
import java.io.*;
import java.net.*;
import java.util.*;
public class App {
    public static void main(String[] args) throws Exception {
        try {
            Socket toOReilly = new Socket("www.oreilly.com", 80);
            // send and receive data...
            System.out.println("IP:"+ toOReilly.getInetAddress()) ;
            System.out.println("local port:"+ toOReilly.getLocalPort()) ;
            System.out.println("Port:"+ toOReilly.getPort()) ;
            System.out.println("InputStream:"+ toOReilly.getInputStream()) ;
            System.out.println("OutStream:"+ toOReilly.getOutputStream()) ;
            } catch (UnknownHostException ex) {
            System.err.println(ex);
            } catch (IOException ex) {
            System.err.println(ex);
            }
} }
Prepared by: Eng/ Basma Elshoky
Example 2: Find out which of the first 1024 ports seem to be hosting TCP servers
on a specified host
import java.io.*;
import java.net.*;
import java.util.*;
public class App {
    public static void main(String[] args) throws Exception {
        String host = args.length > 0 ? args[0] : "localhost";
        for (int i = 1; i < 1024; i++) {
        try {
        Socket s = new Socket(host, i);
        System.out.println("There is a server on port " + i + " of "
        + host);
        s.close();
        } catch (UnknownHostException ex) {
        System.err.println(ex);
        break;
        } catch (IOException ex) { }
     } } }
Prepared by: Eng/ Basma Elshoky
Lab 2:
Create a connection with btu website “Constructing Without Connecting “ then
apply other methods in the table.
Some help: this mean you need using connection method and SocketAddress
class.
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress("domain", “port”);
socket.connect(address);
Next Section: Socket for servers.
Reference: Harold, Elliotte Rusty. "Java Network Programming", Chapter 9:
Sockets for Clients. O'Reilly.