TCP socket application by via28446


									           TCP socket

Architecture of Client-Server Applications
Java Socket Programming
Client Application
Server Application

Evolution of Application Architectures

 Java – is one of the earliest programming
  language to support 3-tier and n-tier
 Java’s strength is in developing enterprise
  software (J2EE) as it simplify developer’s
  job in implementing the newer application
  architecture – from 3-tier to n-tier to mobile.

3-tier Client-Server Application

A Bug Tracking System (3-tier)

Socket-based Client-Server
 Application : ALI BABA

               TCP overview
   Unlike UDP which is concerned with the
    transmission of packets of data, TCP
    establishes a "virtual connection" between
    two machines through which streams of
    data may be sent.
   TCP guarantees delivery and order,
    providing a reliable byte communication
    stream between client and server that
    supports two-way communication.
Establish a virtual connection

Transmit data back and forth

Terminate the connection

   TCP uses IP (Internet Protocol) to establish
    the connection between machines.
   This connection provides an interface that
    allows streams of bytes to be sent and
    received, and transparently converts the
    data into IP datagram packets.
   The virtual connection between two
    machines is represented by a socket.

               What is a socket?
   Original idea came from UNIX
   “The network is just like a file system”
   Read and write a stream of data “to the
    network” through socket
   Stream? ( recall : using package )
   A socket is bound to a port number so that the
    TCP layer can identify the correct application
    for the data

                A little background
   Socket provides the TCP/IP communication
       Introduced in 1981- UNIX BSD 4.2
       Later Sun build RPC and NFS over the socket
   Is supported by all OS
       WinSocks for Windows 3.1
       Built into Windows 95, … and NT
       For other OS – it is not new
   Is the De Facto in network communication

 Communication between processes :
      using port and socket
                                                  agreed port
                                   any port
            socket                                                             socket


              client                                                           server

                                          other ports

Internet address =                                Internet address =

              • Port: The destination of a message
              • Socket: The final point for processes communication
              • Each socket is associated with UDP or TCP

   Like ports in UDP, ports in TCP are also
    represented by a number in the range 1 - 65535.
   Ports below 1024 are restricted to use by well-
    known services. For example,
       Telnet (port 23)
       SMTP (port 25)
       HTTP (port 80)
       POP3 (port 110)

                   TCP vs UDP
   TCP sockets are different from UDP
       TCP sockets are connected to a single machine.
       UDP sockets only send and receive packets of
       TCP allows transmission of data through byte
        streams. They are converted into datagram
        packets for transmission over the network
        without programmer intervention.

     Advantages of TCP over UDP
   Automatic Error Control
       Data transmission is more dependable. Delivery
        of data is guaranteed - lost data packets are
       By means of a timer, TCP retransmits a packet if
        an acknowledgement is not received from the
        recipient within a specified amount of time.

   Reliability
       As packets are delivered by IP, they will
        frequently arrive out of order. However, each
        packet contains a sequence number. Using this
        sequence number and queuing out-of-order
        packets, TCP is able to pass arriving packets to
        the application in the correct sequence.

   Ease of Use
       Network programmers will find programming
        communication via TCP sockets far simpler than
        via datagram packets. This is because data sent
        and received can be treated as a continuous
        stream (like I/O streams). The data need not be
        packaged into discrete units like UDP.

               Socket Operations
   TCP sockets can perform a variety of
       Establish a connection to a remote host
       Send data to a remote host
       Receive data from a remote host
       Close a connection

   There is a special type of socket that
    provides a service that will bind to a
    specific port number. Normally used only
    in servers, this socket can perform the
    following operations:
       Bind to a local port
       Accept incoming connections from remote hosts
       Unbind from a local port

    TCP and the Client/Server Paradigm
   In network programming, applications that
    use sockets are divided into clients and
   A client is software that initiates a
    connection and sends requests.
   A server is software that listens for
    connections and processes requests.

   Note that in the context of UDP
    programming, no actual connection is
    established. UDP applications may both
    initiate and receive requests on the same
   In the client/server paradigm, when there is
    a connection between two applications, one
    must be a client and the other must be a
               Network Clients
   Network clients initiate connections and
    control network transactions.
   The server fulfills the requests of the client
    but not the other way round.
   The network client speaks to the server
    using a network protocol. E.g an HTTP
    client communicates with an HTTP server
    using HTTP.

   Port numbers are used to enable clients to
    locate server applications. E.g. a web
    server uses port 80.

                Network Servers
   The role of the network server is to bind to a
    specific port and to listen for new connections.
   Unlike the client, the server must run continually
    in the hope that some client will want its services.
   The server runs indefinitely. Normally, it is
    automatically started when the host computer of
    the server is started.

   Some servers can handle only one connection at
    a time, while others can handle many connections
    concurrently, through the use of threads.
   Some protocols (e.g. HTTP/1.0) normally allow
    only one request per connection. Others, like
    POP3, support a sequence of requests.
   Servers answer the client request by sending
    either a response or an error message.

                  Socket Types
   In Java, there are 4 main socket types:
       ServerSocket
       Socket
       DatagramSocket
       MulticastSocket
   Accessible by importing*;

           TCP Sockets and Java
   Java provide the following classes for TCP
   The Socket class should be used when
    writing client software.
   The ServerSocket class should be used
    when writing server software.

               Socket Class

   Socket objects represent client sockets,
    and is a communication channel between
    two TCP communications ports belonging
    to one or two machines.

   There are several constructors for the
    Socket class.
   The easiest way to create a socket is
    shown below:
       Socket mySocket;
       try {
         mySocket = new Socket("",
       } catch (Exception e) {

                      Socket Constructors
   From 8 constructors, 4 are commonly used:

   public Socket(InetAddress address, int port)
        Throws, java.lang.SecurityException
    Creates a stream socket and connects it to the specified port number at the specified IP
   public Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
        Throws, java.lang.SecurityException
    Creates a socket and connects it to the specified remote address on the specified remote

   public Socket(String host, int port)
        Throws, java.lang.SecurityException
    Creates a stream socket and connects it to the specified port number on the named host.

   public Socket(String host, int port, InetAddress localAddr, int localPort)
        Throws,,
    Creates a socket and connects it to the specified remote host on the specified remote

    Reading from and Writing to TCP
   In Java, once a socket is created, it is
    connected and ready to read/write by using
    the socket's input and output streams. Use
    the methods getInputStream() and
    getOutputStream() to access those

 Example:

Socket socket;
InputStreamReader isr;
BufferedReader br;
PrintStream ps;
try {
   socket = new Socket("",80);
  isr = new InputStreamReader(socket.getInputStream());
  br = new BufferedReader(isr);

  ps = new PrintStream(socket.getOutputStream());
} catch (Exception e) {
            Methods of class Socket
public InputStream getInputStream();                Returned stream
Returns an input stream for this socket.             depends on TCP flow
                                                     control and error
 public OutputStream getOutputStream();
Returns an output stream for this socket.            correction.

 public void close();
Closes this socket.

public int getPort();
Returns a remote port associated to the socket.

public InetAddress getInetAddress();
Returns an address associated to the socket.

public int getLocalPort();
Returns a local port associated to the socket.

                 Server Socket
   Server socket is bound to a certain port of a
    local host
   When it is successfully bound to a port, it
    immediately listens to any attempt of incoming
   When a server detects an attempt of incoming
    connection, it accept the connection
   This creates a socket which handles
    communication between the client and server

          ServerSocket Class
 represents the
  serve socket
 ServerSocket object is created on a local
  port and calls method accept() to listen to
  incoming connection
 accept() will block until a connection is
  detected. Then it returns a Socket object
  that handles communication with a client

   The easiest way to create a socket to listen
    at a certain port is shown below:
       ServerSocket mySocket;
       try {
         mySocket = new ServerSocket(80);
       } catch (Exception e) {

         ServerSocket Constructors
   Some of the other constructors:
       ServerSocket(int port)
            Throws,
            If port is 0, then any free port will be used.
            By default, the queue size is set to 50.
       ServerSocket(int port, int maxClients)
            Throws,
            Allocates sufficient space to the queue to support
             the specified number of client sockets.

     Methods of class ServerSocket
   public Socket accept();
       Listens for a connection to be made to this socket
        and accepts it.

   public void close();
       Closes this socket.

   public InetAddress getInetAddress();
       Returns the local address of this server socket.

   When a ServerSocket object is created, it
    attempts to bind to the port on the local host given
    by the port argument.
   If another server socket is already listening to the
    port, then a, a subclass of
    IOException, is thrown.
   No more than one process or thread can listen to
    a particular port at a time. This includes non-Java
    processes or threads.
   For example, if there's already an HTTP server
    running on port 80, you won't be able to bind to
    port 80.

   If you want your process to wait (listening) incoming
    connections at a specified port, ServerSocket class
    allow it to detect the incoming connection:

    ServerSocket outSock = new ServerSocket
    while (true) {
       Socket inSock = outSock.accept();

    Accepting and Processing Requests
            from TCP Clients
   The most important function of a server socket is
    to accept client sockets. Once a client socket is
    obtained, the server can perform all the "real
    work" of server programming, which involves
    reading from and writing to the socket to
    implement a network protocol.
   Example: a mail server that provides access to
    stored messages would listen to commands and
    send back message contents.

 Example:

ServerSocket server;
BufferedReader reader;
PrintWriter writer;
server = new ServerSocket(13);
while (true) {
     Socket client = server.accept();
     reader = new BufferedReader(
               new InputStreamReader(
     writer = new PrintWriter(
               new OutputStreamWriter(
ALI BABA Client-Server Apps

            Client Application
   The example consists of two applications
    which is executed separately
   The client app is implemented as
    NyietInSengClient class

import*;                                          BufferedReader stdIn = new
import*;                                          BufferedReader(new
public class NyietInSengClient {                             String fromServer;
  public static void main(String[] args)                     String fromUser;
  throws IOException {
     Socket nisSocket = null;                                   while ((fromServer = in.readLine()) != null) {
     PrintWriter out = null;                                      System.out.println("Server: " +
     BufferedReader in = null;                                    if (fromServer.equals("tata titi tutu"))
     try {
        nisSocket = new Socket("localhost", 8888);                  fromUser = stdIn.readLine();
        out = new                                                 if (fromUser != null) {
    PrintWriter(nisSocket.getOutputStream(), true);
        in = new BufferedReader(new                                    System.out.println("Client: " +
    InputStreamReader(nisSocket.getInputStream()));            fromUser);
     } catch (UnknownHostException e) {                                out.println(fromUser);
        System.err.println("Don't know about host:                }
    localhost.");                                               }
     } catch (IOException e) {                                  out.close();
        System.err.println("Couldn't get I/O for the            in.close();
    connection to: localhost.");                                stdIn.close();
        System.exit(1);                                         nisSocket.close();
     }                                                     }

                  Server Application
   Server app is implemented using 2 classes:
       NyietInSengServer
            NyietInSengServer contains the main() method for
             the server app. It listens at a port, accepts
             connection, read from and write to the socket.

import*;                                          PrintWriter out = new
                                                             PrintWriter(clientSocket.getOutputStream(), true);
                                                              BufferedReader in = new BufferedReader(
public class NyietInSengServer {                             InputStreamReader(clientSocket.getInputStream()
  public static void main(String[] args) throws              ));
   IOException {                                              String inputLine, outputLine;
                                                              NyietInSengProtocol nis = new
     ServerSocket serverSocket = null;
     try {                                                      outputLine = nis.processInput(null);
        serverSocket = new ServerSocket(8888);                  out.println(outputLine);
     } catch (IOException e) {
        System.err.println("Could not listen on                 while ((inputLine = in.readLine()) != null) {
    port: 8888.");                                                  outputLine = nis.processInput(inputLine);
        System.exit(1);                                             out.println(outputLine);
                                                                    if (outputLine.equals("tata titi tutu"))
     Socket clientSocket = null;                                out.close();
     try {                                                      in.close();
        clientSocket = serverSocket.accept();                   clientSocket.close();
     } catch (IOException e) {                                  serverSocket.close();
        System.err.println("Accept failed.");               }

               Server Application
   NyietInSengProtocol
       NyietInSengProtocol provides the jokes. It tracks
        the current joke, current status (SENTTOKTOK,
        SENTCLUE, etc) and returns jokes text based on
        the current status.
       It implements the communication protocol agreed
        by the client and server.

             Server Application
  The server app begins by creating a ServerSocket
   object to listen (wait) at a specified port. When
   selecting a port number use the one not defined for
   other services. NyietInSengServer waits at port 8888
   because 8/8 is my birthdate (ONG) and port 8888 is not
   used in my computer environment
try {
   serverSocket = new ServerSocket(8888);
catch (IOException e) {
   System.out.println("Could not listen on port: 8888");

             Server Application
   Constructor ServerSocket throws an
    exception if it cannot listen to the specified
    port (in used).
   In this kes NyietInSengServer has no other
    choice than to end the program. (exit).

   If server manage to connect to the specified
    port, then a ServerSocket object is created and
    the next step is executed- accept client
    connection (bold):
    Socket clientSocket = null;
    try {
       clientSocket = serverSocket.accept();
    } catch (IOException e) {
       System.out.println("Accept failed: 8888");

             Server Application
   accept() waits until client program is executed
    and request for connection to host and port. (In
    example: host : localhost and port : 8888.
   When connection is successful, method
    accept() will return a new Socket object (i.e
    :clientSocket) which is bound to a new port.
   Server program can communicate with client via
    this new socket. It can continue waiting for the
    next incoming call through the original
    ServerSocket object (in the program :
   Nevertheless in this example, server app cannot
    wait for more than 1 client
1.   Gets the socket's input and output stream
     and opens readers and writers on them
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
BufferedReader in = new BufferedReader( new InputStreamReader(
String inputLine, outputLine;

2.   After the server successfully establishes a
     connection with a client, it communicates
     with the client using this code:
    // initiate conversation with client
NyietInSengProtocol nis = new NyietInSengProtocol();
outputLine = nis.processInput(null);

while ((inputLine = in.readLine()) != null) {
   outputLine = nis.processInput(inputLine);
   if outputLine.equals(“tata titi tutu"))
3. Communicates with the client by reading
     from and writing to the socket (the while
   1 is already familiar. Step 2 is shown in bold and
    is worth a few comments.
   After the NyietInSengProtocol is created, the
    code calls NyietInSengProtocol 's processInput
    method to get the first message that the server
    sends to the client.
   For this example, the first thing that the server
    says is “NyietInSeng MatekAji Semar Ngiseng!"
    Next, the server writes the information to the
    PrintWriter connected to the client socket,
    thereby sending the message to the client.

AliBaba Communication Protocol
   Following is the class implementation of the

import*;                                       if (state == WAITING) {
import*;                                            theOutput = "NyietInSeng MatekAji Semar Ngiseng!";
                                                             state = SENTTOKTOK;
                                                          } else if (state == SENTTOKTOK) {
public class NyietInSengProtocol {                           if (theInput.equalsIgnoreCase("Siapa tu?")) {
                                                                 theOutput = clues[currentJoke];
  private static final int WAITING = 0;                          state = SENTCLUE;
                                                             } else {
  private static final int SENTTOKTOK = 1;                       theOutput = "Sepatutnya awak cakap \"Siapa tu?\"! " +
  private static final int SENTCLUE = 2;                                                     "Cuba lagi. NyietInSeng MatekAji Semar
  private static final int ANOTHER = 3;                      }
                                                          } else if (state == SENTCLUE) {
                                                             if (theInput.equalsIgnoreCase(clues[currentJoke] + " mana?")) {
  private static final int NUMJOKES = 3;                         theOutput = answers[currentJoke] + " Main lagi? (y/n)";
                                                                 state = ANOTHER;
                                                             } else {
  private int state = WAITING;                                   theOutput = "Sepatutnya awak cakap \"" +
                                                                                             clues[currentJoke] +
  private int currentJoke = 0;                                                               " mana?\"" +
                                                                                             "! Cuba lagi. NyietInSeng MatekAji Semar
  private String[] clues =                                       state = SENTTOKTOK;
   { "Ali", "Di Sini", "Hari"};                           } else if (state == ANOTHER) {
                                                             if (theInput.equalsIgnoreCase("y")) {
  private String[] answers =                                     theOutput = "NyietInSeng MatekAji Semar Ngiseng!";
   { "Ali Baba, Bujang Lapok la.. ",                             if (currentJoke == (NUMJOKES - 1))
                                                                     currentJoke = 0;
     "Di Sini lah, Oi Di Sana! ",                                else
     "Harimau Kuat! Grrrrrr "};                                      currentJoke++;
                                                                 state = SENTTOKTOK;
                                                             } else {
                                                                 theOutput = "tata titi tutu";
  public String processInput(String theInput) {                  state = WAITING;
    String theOutput = null;                                 }
                                                          return theOutput;

To top