TCP socket application by via28446

VIEWS: 13 PAGES: 58

									           TCP socket
           application

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




                   norly@ftsm.ukm.my          1
Evolution of Application Architectures




                norly@ftsm.ukm.my
                                     2
 Java – is one of the earliest programming
  language to support 3-tier and n-tier
  architecture.
 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.




                     norly@ftsm.ukm.my
                                                    3
3-tier Client-Server Application




              norly@ftsm.ukm.my
                                   4
A Bug Tracking System (3-tier)




             norly@ftsm.ukm.my
                                 5
Socket-based Client-Server
 Application : ALI BABA




          norly@ftsm.ukm.my
                              6
               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.
                      norly@ftsm.ukm.my
                                                 7
Establish a virtual connection

Transmit data back and forth



Terminate the connection




          norly@ftsm.ukm.my
                                 8
   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.

                      norly@ftsm.ukm.my
                                               9
               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 java.io )
   A socket is bound to a port number so that the
    TCP layer can identify the correct application
    for the data

                        norly@ftsm.ukm.my
                                                     10
                A little background
   Socket provides the TCP/IP communication
    protocol
       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

                             norly@ftsm.ukm.my
                                                      11
 Communication between processes :
      using port and socket
                                                  agreed port
                                   any port
            socket                                                             socket



                                              message

              client                                                           server

                                          other ports


Internet address = 138.37.94.248                                Internet address = 138.37.88.249

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


                                         norly@ftsm.ukm.my
                                                                                                   12
   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)



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


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



                          norly@ftsm.ukm.my
                                                       15
   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.




                           norly@ftsm.ukm.my
                                                           16
   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.




                          norly@ftsm.ukm.my
                                                      17
               Socket Operations
   TCP sockets can perform a variety of
    operations:
       Establish a connection to a remote host
       Send data to a remote host
       Receive data from a remote host
       Close a connection




                          norly@ftsm.ukm.my
                                                  18
   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

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

                     norly@ftsm.ukm.my
                                                20
   Note that in the context of UDP
    programming, no actual connection is
    established. UDP applications may both
    initiate and receive requests on the same
    socket.
   In the client/server paradigm, when there is
    a connection between two applications, one
    must be a client and the other must be a
    server.
                      norly@ftsm.ukm.my
                                               21
               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.

                       norly@ftsm.ukm.my
                                                     22
   Port numbers are used to enable clients to
    locate server applications. E.g. a web
    server uses port 80.




                      norly@ftsm.ukm.my
                                                 23
                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.



                          norly@ftsm.ukm.my
                                                           24
   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.


                        norly@ftsm.ukm.my
                                                   25
                  Socket Types
   In Java, there are 4 main socket types:
       ServerSocket
       Socket
       DatagramSocket
       MulticastSocket
   Accessible by importing java.net.*;



                          norly@ftsm.ukm.my
                                              26
           TCP Sockets and Java
   Java provide the following classes for TCP
    sockets:
       java.net.Socket
       java.net.ServerSocket
   The Socket class should be used when
    writing client software.
   The ServerSocket class should be used
    when writing server software.

                      norly@ftsm.ukm.my
                                                 27
               Socket Class

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




                     norly@ftsm.ukm.my
                                               28
   There are several constructors for the
    Socket class.
   The easiest way to create a socket is
    shown below:
       Socket mySocket;
       try {
         mySocket = new Socket("www.aol.com",
         80);
       } catch (Exception e) {
         …
       }

                      norly@ftsm.ukm.my
                                                29
                      Socket Constructors
   From 8 constructors, 4 are commonly used:

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

   public Socket(String host, int port)
        Throws java.io.IOException, 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 java.net.UnknownHostException, java.io.IOException,
         java.lang.SecurityException
    Creates a socket and connects it to the specified remote host on the specified remote
    port.




                                              norly@ftsm.ukm.my
                                                                                               30
    Reading from and Writing to TCP
                Sockets
   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
    streams.



                     norly@ftsm.ukm.my
                                             31
 Example:

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

  ps = new PrintStream(socket.getOutputStream());
} catch (Exception e) {
    …
}
                        norly@ftsm.ukm.my
                                                    32
            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.

                                 norly@ftsm.ukm.my
                                                                           33
                 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
    connection
   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

                        norly@ftsm.ukm.my
                                                     34
          ServerSocket Class
 java.net.ServerSocket 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

                    norly@ftsm.ukm.my
                                                35
   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) {
         …
       }


                      norly@ftsm.ukm.my
                                               36
         ServerSocket Constructors
   Some of the other constructors:
       ServerSocket(int port)
            Throws java.io.IOException,
             java.lang.SecurityException
            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 java.io.IOException,
             java.lang.SecurityException
            Allocates sufficient space to the queue to support
             the specified number of client sockets.

                               norly@ftsm.ukm.my
                                                                  37
     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.


                              norly@ftsm.ukm.my
                                                             38
   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 java.net.BindException, 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.

                         norly@ftsm.ukm.my
                                                       39
   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
    (8888);
    while (true) {
       Socket inSock = outSock.accept();
            handleConnection(inSock);
            inSock.close();
     }



                            norly@ftsm.ukm.my
                                                            40
    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.

                         norly@ftsm.ukm.my
                                                        41
 Example:

ServerSocket server;
BufferedReader reader;
PrintWriter writer;
server = new ServerSocket(13);
while (true) {
     Socket client = server.accept();
     reader = new BufferedReader(
               new InputStreamReader(
               client.getInputStream()));
     writer = new PrintWriter(
               new OutputStreamWriter(
               client.getOutputStream()));
     …
}                    norly@ftsm.ukm.my
                                             42
ALI BABA Client-Server Apps




           norly@ftsm.ukm.my
                               43
            Client Application
   The example consists of two applications
    which is executed separately
   The client app is implemented as
    NyietInSengClient class




                     norly@ftsm.ukm.my
                                               44
import java.io.*;                                          BufferedReader stdIn = new
import java.net.*;                                          BufferedReader(new
                                                            InputStreamReader(System.in));
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: " +
                                                               fromServer);
     BufferedReader in = null;                                    if (fromServer.equals("tata titi tutu"))
                                                                      break;
     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.");                                               }
        System.exit(1);
     } 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();
     }                                                     }
                                                       }

                                              norly@ftsm.ukm.my
                                                                                                         45
                  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.




                             norly@ftsm.ukm.my
                                                            46
import java.net.*;                                          PrintWriter out = new
                                                             PrintWriter(clientSocket.getOutputStream(), true);
import java.io.*;
                                                              BufferedReader in = new BufferedReader(
                                                                                            new
public class NyietInSengServer {                             InputStreamReader(clientSocket.getInputStream()
  public static void main(String[] args) throws              ));
   IOException {                                              String inputLine, outputLine;
                                                              NyietInSengProtocol nis = new
                                                             NyietInSengProtocol();
     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"))
     }
                                                                       break;
                                                                }
     Socket clientSocket = null;                                out.close();
     try {                                                      in.close();
        clientSocket = serverSocket.accept();                   clientSocket.close();
     } catch (IOException e) {                                  serverSocket.close();
        System.err.println("Accept failed.");               }
                                                        }
        System.exit(1);
     }


                                                norly@ftsm.ukm.my
                                                                                                           47
               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.



                          norly@ftsm.ukm.my
                                                        48
             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");
    System.exit(-1);
}

                         norly@ftsm.ukm.my
                                                        49
             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).




                       norly@ftsm.ukm.my
                                                     50
   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");
       System.exit(-1);
    }



                             norly@ftsm.ukm.my
                                                      51
             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 :
    serverSocket)
   Nevertheless in this example, server app cannot
    wait for more than 1 client
                        norly@ftsm.ukm.my
                                                   52
                      Read/Write
1.   Gets the socket's input and output stream
     and opens readers and writers on them
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
     true);
BufferedReader in = new BufferedReader( new InputStreamReader(
     clientSocket.getInputStream()));
String inputLine, outputLine;




                             norly@ftsm.ukm.my
                                                                    53
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);
out.println(outputLine);




                               norly@ftsm.ukm.my
                                                   54
while ((inputLine = in.readLine()) != null) {
   outputLine = nis.processInput(inputLine);
   out.println(outputLine);
   if outputLine.equals(“tata titi tutu"))
       break;
}
3. Communicates with the client by reading
     from and writing to the socket (the while
     loop).
                     norly@ftsm.ukm.my
                                                 55
   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.

                        norly@ftsm.ukm.my
                                                     56
AliBaba Communication Protocol
   Following is the class implementation of the
    protocol




                      norly@ftsm.ukm.my
                                               57
import java.net.*;                                       if (state == WAITING) {
import java.io.*;                                            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
                                                            Ngiseng!";
  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
                                                            Ngiseng!";
  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;
                                                         }
                                                      }
                                             norly@ftsm.ukm.my
                                                                                                                         58

								
To top