Document Sample
Socket Powered By Docstoc
					   Client-Server and
  Socket Programming

Pemrograman Jaringan dan Web
      (Ahmad Nasikun)
          Week 2
            What To do today?
   Random students' presentation
   Class
   Final project talk
                 Case Study
   DIE HARD 4
          A Communication Model
   Source
              Producing data to be transmitted
   Transmitter
              Converting data into signal, transferable into media
   Transmission System
              Data transmission system
   Receiver
              Converting received signal into understandable data
   Destination
              Consuming received data
            Fundamental Terms
   Connection: a two way communication
    channel between two processes
   Socket: one end of a connection
   Client: connection initiator
   Server: connection acceptor
   Message: a meaningful and complete set
    of bytes
What Can a Network Program Do?
   Networking adds a lot of power to simple programs.
   Network applications generally take one of several forms.
             Client-server:In the simplest case, clients retrieve data from a
              server and display it.
             More complex clients filter and reorganize data, repeatedly
              retrieve changing data, send data to other people and
              computers, and interact with peers in real time for chat,
              multiplayer games, or collaboration. Servers respond to requests
              for data.
             Simple servers merely look up some file and return it to the
             but more complex servers often do a lot of processing on the
              data before answering an involved question.
             Peer-to-peer applications such as BitTorrent connect many
              computers, each of which acts as both a client and a server.
         Network Program Can....
   Retrieve Data ==> Web Browser, RSSReader
   Send Data    ==> FTP, File Storage (Flickr, Youtube)
   Peer-to-Peer Interaction ==> online games,
    chat/messenger, Torrent
   Servers ==> Email server, Web server, file server
   Searching the Web ==> spiders, crawlers (indexing)
   Electronic Commerce
   Ubiquitous Computing ==> JINI (Digital office)
   Interactive Television ==> set-top box; Java TV API
           Networking Concept
   Each and every machine in network is
    called “node”
          Computer, printer, router, bridge, etc
   Some of them are “host” ==> end system
          PC, laptop, smart phone, tablet
   Each node has unique IP address
          Manually (Standard Sub-netting, VLSM)
          DHCP configuration
            Data Transmission
   Circuit Switching
   Packet Switching
                  Circuit Switching
   One line, one communication
   Inefficient
           Capacity is dedicated for 1 channel
           Idle==> capacity + time is mubazir
   Fixed data rate
               Packet Switching
   Data transmitted in small packets
           Longer messages split into series of packets
   Store and forward
           Packets are received, stored briefly
            (buffered) and past on to the next node
                                TCP vs UDP
                       TCP                                         UDP
       Provides the ability to acknowledge        Is an unreliable protocol that does not
        receipt of IP packets and request           guarantee that packets will arrive at
        retransmission of lost or corrupted         their destination.
                                                   Allow the receiver to detect corrupted
       Allows the received packets to be put       packets but does not guarantee that
        back together in the order they were        packets are delivered in the correct
        sent.                                       order.
       Requires a lot of overhead                 Requires less overhead and faster.
       Supported classes in :            Supported classes in :
       URL, URLConnection, Socket, and            DatagramPacket, DatagramSocket,and
        ServerSocket                                MulticastSocket
             Client-Server Model
   Remember the term “Distributed System”
           "A system in which hardware or software
            components located at networked computers
            communicate and coordinate their actions only
            by message passing." [Coulouris]
   Why?
           Resource Sharing
           Workload Sharing
           Platform independen
           Eficience
                    Client Server
   C/S: computer's ability to request data service to
    other computer(s)
            Client: requesting service
            Server: providing service
   C/S: separated process/logic items working together
    within a computer networks to collaboratively conduct
           Service
           Shared resource
           Asymmetrical protocol: one-to-many (one server many clients)

   Transparency location: C/S can be in same or
    different computer
   Mix-and-match/platform independent
               Characteristics (2)
   Message-based-exchange : communicate via
    message exchange
   Encapsulation of service: messages tell the servers
    what to do
   Scalability: C/S system can be scaled up/down
   Integrity: server's data and code are managed in a
    central system, while clients' are on distributed hosts
        Characteristics of a client
   Initiates requests
   Waits for and receives replies
   Usually connects to a small number of
    servers at one time
   Typically interacts directly with end-users
    using a graphical user interface
        Characteristics of a server
   Passive (slave)
   Waits for requests from clients
   Upon receipt of requests, processes them and then
    serves replies
   Usually accepts connections from a large number of
   Typically does not interact directly with end-users
   C/S can create computation rules and roles in distributed
   Easy to maintain (easy to remove, replace, and add
    clients or servers)
   All data are stored in servers, only authorized users can
    access such data
   Centralized storage system, therefore it's easy to update
   Support various clients with different capacity
   Traffic congestion on the network ==> DoS
           P2P, more users higher bandwidth
   There's a possibility of server's failure
           In P2P, some failures still tolerable
   Each port from the server can be treated by the clients as a separate
    machine offering different services.
   Port numbers are represented by 16-bit numbers. (0 to 65,535)
   The port numbers ranging from 0 - 1023 reserved for use by well-
    known services such as HTTP and FTP and other system services.
              ftp   21/tcp
              telnet 23/tcp
              smtp 25/tcp
              login 513/tcp
Time for some Java....
Sockets provide an interface for programming networks at
  the transport layer.
Network communication using Sockets is very much similar
  to performing file I/O
   In fact, socket handle is treated like file handle.
   The streams used in file I/O operation are also applicable to socket-
    based I/O
Socket-based communication is programming language
   That means, a socket program written in Java language can also
    communicate to a program written in Java or non-Java socket
   You can reach required service via its network and
    port IDs. What then?
a) If you are a client
           you need an API that will allow you to send
            messages to that service and read replies from
b) If you are a server
           you need to be able to create a port and listen at it.
           you need to be able to read the message comes in
            and reply to it.
The Socket and ServerSocket are the Java client and server
  classes to do this.
             Socket Communication
A server (program) runs on a specific computer and has a socket that is bound to a
specific port. The server waits and listens to the socket for a client to make a
connection request.

                                   Connection request


    Sockets and Java Socket Classes
A socket is an endpoint of a two-way communication link
between two programs running on the network.
A socket is bound to a port number so that the TCP layer can
identify the application that data destined to be sent.
Java’s .net package provides two classes:
         Socket – for implementing a client
         ServerSocket – for implementing a server

                  Java Sockets
Server    ServerSocket(1234)

         Output/write stream                         Client

         Input/read stream
                               Socket(“”, 1234)
 It can be host_name like “”               27
   The Socket class represents a client socket. Each Socket
    object is associated with exactly one remote host. To
    connect to a different host, you must create a new Socket

           Socket sock= new Socket(ip,port);
      } catch(IOException ioe){
   The ServerSocket class represents a server socket. It is
    constructed on a particular port.
   Then it calls accept() to listen for incoming connections.
    accept() call blocks until a connection request is detected
    on the specified port.
     try {
          int port = 80;
           ServerSocket sersock = new ServerSocket(port);
           Socket sock = sersock.accept();
     } catch(IOException ioe){
         Input and output streams
   Once a socket has connected you send data to the server
    via an output stream. You receive data from the server via
    an input stream.
   Methods getInputStream() and getOutputStream() of
    class Socket.
Reading text from a socket

BufferedReader br = new BufferedReader(new
String str;
while ((str = br.readLine()) != null) {
Writing text to a socket

 BufferedWriter bw = new BufferedWriter(new
                    Secure Socket
   Starting from JDK 1.4, Java Secure Sockets Extension (JSSE)
    is part of the standard distribution.
   JSSE uses the Secure Sockets Layer (SSL) Version 3 and
    Transport Layer
   Security (TLS) protocols and their associated algorithms to
    secure network communications.
   JSSE abstracts all the low-level details such as keys
    exchange,authentication, and data encryption. All you have to
    do is to send your data over the streams from the secured
    sockets obtained.

Shared By: