Socket_OverView1
 
  • A socket is a reliable connection for the transmission of data between two hosts.
  • Sockets isolate programmers from the details of packet encodings, lost and retransmitted packets, and packets that arrive out of order.
  • There are limits. Sockets are more likely to throw  than files, for example.
    • There are four fundamental operations a socket performs. These are:
      • Connect to a remote machine
      • Send data
      • Receive data
      • Close the connection

       

    • A socket may not be connected to more than one host at a time.
    • A socket may not reconnect after it's closed.
    • allows you to create socket objects that perform all four fundamental socket operations.
    • You can connect to remote machines; you can send data; you can receive data; you can close the connection.
    • EachSocket object is associated with exactly one remote host. To connect to a different host, you must create a new Socket object.
    • Connection is accomplished through the constructors.
      • public Socket(String host, int port) throws UnknownHostException,
        IOException
      • public Socket(InetAddress address, int port) throws IOException
      • public Socket(String host, int port, InetAddress localAddr, int localPort)
        throws IOException
      • public Socket(InetAddress address, int port, InetAddress localAddr, int
        localPort) throws IOException
    • The constructors do not just create a Socket object. They also attempt to connect the underlying socket to the remote server.
    • All the constructors throw an IOException if the connection can't be made for any reason.
    • You must at least specify the remote host and port to connect to.
    • The host may be specified as either a string like "utopia.poly.edu" or as an InetAddress object.
    • The port should be an int between 1 and 65535.Socket webMetalab = new Socket("metalab.unc.edu", 80);
    • You cannot just connect to any port on any host. The remote host must actually be listening for connections on that port.
    • You can use the constructors to determine which ports on a host are listening for connections.
    • Choosing a local port
    • You can also specify a local port number,
    • Setting the port to 0 tells the system to randomly choose an available port.
    • If you need to know the port you're connecting from, you can always get it with getLocalPort().

      Socket webMetalab = new Socket("metalab.unc.edu", 80, "calzone.oit.unc.edu", 0);

    Sending and Receiving Data
    • Data is sent and received with output and input streams.
    • There are methods to get an input stream for a socket and an output stream for the socket.
      public InputStream  getInputStream()
       throws IOException
      
      public OutputStream getOutputStream()
       throws IOException
      

       

    • There's also a method to close a socket:

      public synchronized void close() throws IOException

    Reading Input from a Socket
    • The getInputStream() method returns an InputStream which reads data from the socket.
    • You can use all the normal methods of the InputStream class to read this data.
    • Most of the time you'll chain the input stream to some other input stream or reader object to more easily handle the data.

    Reading Data with a Server Socket:

    • Server Socket uses accept() method to receive a client. May throw the following exceptions:
      public Socket accept() throws IOException
    • There are not getInputStream() or getZOutputStream() methods for server socket
    • accept method returns a Socket Object and its getInputStream() and getOutputStream() methods provide streams.
      try {
      ServerSocket ss = new ServerSocket(5216);
      Socket s = ss.accept();
      PrintWriter pw = new
      PrintWriter(s.getOutputStream());
      pw.println("Print message 1!");
      pw.println("Print message 2");
      s.close();
      }
      catch (IOException e) {
      System.err.println(e);
      }
    Writing Output to a Socket (Client)
    • The getOutputStream() method returns an output stream which writes data to the socket.
    • Most of the time you'll chain the raw output stream to some other output stream or writer class to more easily handle the data.

    Reading Data

    Reading and Writing to a Socket http://www.cafeaulait.org/slides/sd2000east/sockets/23.html
    • It's unusual to only read from a socket. It's even more unusual to only write to a socket.
    • Most protocols require the client to both read and write.
    • Some protocols require the reads and the writes to be interlaced. That is:
       
        HTTP1.0 multiple writes
      write
      read
      write
      read
      write
      read
      write
      write
      write
      read
      read
      read
      read
       
    • Java places no restrictions on reading and writing to sockets.
    • One thread can read from a socket while another thread writes to the socket at the same time.
    Socket Options:
    • public void setTcpNoDelay(boolean on)
       throws SocketException
    • public boolean getTcpNoDelay() t
      hrows SocketException
    • public void setSoLinger
      (boolean on, int val) 
      throws SocketException
    • public int getSoLinger() 
      throws SocketException
    • public void setSoTimeout(int timeout)
       throws SocketException
    • public int getSoTimeout() 
      throws SocketException
    • These methods to return information about the socket:

      public InetAddress getInetAddress()
      public InetAddress getLocalAddress()
      public int getPort()
      public int getLocalPort()

      Finally there's the usual toString() method:

      public String toString()
    Socket Client Server:
    • There are two ends to each connection: the client, that is the host that initiates the connection, and the server, that is the host that responds to the connection.
    • Clients and servers are connected by sockets.
    • A server, rather than connecting to a remote host, a program waits for other hosts to connect to it.
    Server Socket
    • A server socket binds to a particular port on the local machine.
    • Once it has successfully bound to a port, it listens for incoming connection attempts.
    • When a server detects a connection attempt, it accepts the connection. This creates a socket between the client and the server over which the client and the server communicate.
    Multiple Clients
    • Multiple clients can connect to the same port on the server at the same time.
    • Incoming data is distinguished by the port to which it is addressed and the client host and port from which it came.
    • The server can tell for which service (like http or ftp) the data is intended by inspecting the port.
    • It can tell which open socket on that service the data is intended for by looking at the client address and port stored with the data.
    Socket Queuing
    • Incoming connections are stored in a queue until the server can accept them.
    • On most systems the default queue length is between 5 and 50.
    • Once the queue fills up further incoming connections are refused until space in the queue opens up.
    • The java.net.ServerSocket Class

      The java.net.ServerSocket class represents a server socket.

      A ServerSocket object is constructed on a particular local port. Then it calls accept() to listen for incoming connections.

      accept() blocks until a connection is detected. Then accept() returns a java.net.Socket object that performs the actual communication with the client.
    The java.net.ServerSocket Class
     
    • The java.net.ServerSocket class represents a server socket.
    • A ServerSocket object is constructed on a particular local port. Then it calls accept() to listen for incoming connections.
    • accept() blocks until a connection is detected. Then accept() returns a java.net.Socket object that performs the actual communication with the client.
    Constructors;
    • There are three constructors that let you specify the port to bind to, the queue length for incoming connections, and the IP address to bind to:
    • public ServerSocket(int port) throws IOException
    • public ServerSocket(int port, int backlog) throws IOException
    • public ServerSocket(int port, int backlog, InetAddress networkInterface) throws IOException