Docstoc

Sockets

Document Sample
Sockets Powered By Docstoc
					Network Programming and
     Java Sockets



       Vijayalakshmi R




                          1
                     Agenda

   Introduction
   Elements of Client Server Computing
   Networking Basics
   Understanding Ports and Sockets
   Java Sockets
       Implementing a Server
       Implementing a Client
   Sample Examples
   Conclusions

                                          2
               Introduction

   Internet and WWW have emerged as global
    ubiquitous media for communication and
    changing the way we conduct science,
    engineering, and commerce.
   They also changing the way we learn, live,
    enjoy, communicate, interact, engage, etc. It
    appears like the modern life activities are
    getting completely centered around the
    Internet.


                                                    3
Internet Applications Serving Local
         and Remote Users

                                      PC client


         Internet
         Server
                    Local Area Network




                                 PD
                                 A
                                                  4
Internet & Web as a delivery Vehicle




                                   5
    Increased demand for Internet
            applications
   To take advantage of opportunities presented by
    the Internet, businesses are continuously seeking
    new and innovative ways and means for offering
    their services via the Internet.
   This created a huge demand for software
    designers with skills to create new Internet-enabled
    applications or migrate existing/legacy applications
    on the Internet platform.
   Object-oriented Java technologies—Sockets,
    threads, RMI, clustering, Web services-- have
    emerged as leading solutions for creating portable,
    efficient, and maintainable large and complex
    Internet applications.
                                                       6
  Elements of C-S Computing

             a client, a server, and network



   Client
                                               Server
                         Network


Client machine
                                         Server machine

                                                          7
              Networking Basics
   Applications Layer              TCP/IP Stack
       Standard apps
            HTTP
            FTP
            Telnet                          Application
       User apps                        (http,ftp,telnet,…)
   Transport Layer
                                             Transport
       TCP
       UDP                                (TCP, UDP,..)
       Programming Interface:                Network
            Sockets
   Network Layer                              (IP,..)
       IP                                      Link
   Link Layer                            (device driver,..)
       Device drivers



                                                               8
            Networking Basics

   TCP (Transport Control        TCP/IP Stack
    Protocol) is a
    connection-oriented                   Application
    protocol that provides a          (http,ftp,telnet,…)
    reliable flow of data
                                          Transport
    between two computers.
                                        (TCP, UDP,..)
   Example applications:                  Network
       HTTP                                (IP,..)
       FTP
                                             Link
       Telnet
                                       (device driver,..)



                                                            9
            Networking Basics

   UDP (User Datagram            TCP/IP Stack
    Protocol) is a protocol
    that sends independent                Application
    packets of data, called           (http,ftp,telnet,…)
    datagrams, from one
                                          Transport
    computer to another with
                                        (TCP, UDP,..)
    no guarantees about
                                           Network
    arrival.
                                            (IP,..)
   Example applications:                    Link
       Clock server
                                       (device driver,..)
       Ping


                                                            10
        Understanding Ports

   The TCP and UDP                      P
                                         o      TCP
    protocols use ports to    server
                                         r            Client
    map incoming data to                 t
    a particular process
    running on a
    computer.
                app    app      app      app


                port   port     port     port
                       TCP or UDP
                                                  Packet
                                       Data        port# data
                                                           11
          Understanding Ports

   Port is represented by a positive (16-bit) integer
    value
   Some ports have been reserved to support
    common/well known services:
       ftp 21/tcp
       telnet 23/tcp
       smtp 25/tcp
       login 513/tcp
   User level process/services generally use port
    number value >= 1024

                                                     12
                         Sockets

   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
    independent.
       That means, a socket program written in Java language can
        also communicate to a program written in Java or non-Java
        socket program.



                                                                        13
      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
              port




     server
                                           Client


                                                    14
      Socket Communication

   If everything goes well, the server accepts the
    connection. Upon acceptance, the server gets a new
    socket bounds to a different port. It needs a new socket
    (consequently a different port number) so that it can
    continue to listen to the original socket for connection
    requests while serving the connected client.
              port




     server




                                             port
                                                    Client
       port            Connection


                                                             15
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
                                                   16
                    Java Sockets
Server       ServerSocket(1234)




           Output/write stream                              Client




           Input/read stream

                                      Socket(“128.250.25.158”, 1234)
         It can be host_name like “mandroo.cs.mu.oz.au”          17
         Socket programming
Goal: learn how to build client/server application
 that communicate using sockets
  Socket API                      socket
     introduced in BSD4.1              a host-local,
      UNIX, 1981                   application-created,
                                  OS-controlled interface
     explicitly created, used,      (a “door”) into which
      released by apps              application process can
                                         both send and
     client/server paradigm
                                  receive messages to/from
     two types of transport          another application
      service via socket API:               process
        unreliable datagram

        reliable, byte stream-
                                                              18
          oriented
   Socket-programming using TCP
 Socket: a door between application process and
   end-end-transport protocol (UCP or TCP)
 TCP service: reliable transfer of bytes from one
   process to another
                                                   controlled by
controlled by                          process     application
  application   process
                                                   developer
   developer     socket                 socket
                TCP with               TCP with    controlled by
controlled by
                                       buffers,    operating
   operating    buffers,    internet               system
      system    variables              variables

                host or                host or
                server                 server

                                                                   19
    Socket programming with TCP
Client must contact server            When contacted by client,
  server process must first be        server TCP creates new
   running
                                       socket for server process
  server must have created
                                       to communicate with
   socket (door) that welcomes
   client’s contact                    client
                                         allows server to talk
Client contacts server by:
  creating client-local TCP               with multiple clients
   socket                                source port numbers

  specifying IP address, port             used to distinguish
   number of server process                clients (more in Chap
  When client creates socket:        application viewpoint
                                           3)
   client TCP establishes
                                      TCP provides reliable, in-order
   connection to server TCP             transfer of bytes (“pipe”)
                                        between client and server
                                                                        20
 Client/server socket interaction: TCP
Server (running on hostid)                    Client
     create socket,
     port=x, for
     incoming request:
     welcomeSocket =
        ServerSocket()

                             TCP             create socket,
     wait for incoming
     connection request connection   setup   connect to hostid, port=x
     connectionSocket =                      clientSocket =
     welcomeSocket.accept()                         Socket()

                                               send request using
     read request from                         clientSocket
     connectionSocket

      write reply to
      connectionSocket                         read reply from
                                               clientSocket
      close
      connectionSocket                          close
                                                clientSocket
                                                                         21
               Stream jargon
                                             keyboard            monitor


   A stream is a sequence
    of characters that flow




                                                   inFromUser
                                           input
                                          stream
    into or out of a process.   Client
                                Process
   An input stream is          process
    attached to some input
    source for the process,
    e.g., keyboard or socket.




                                                                    inFromServer
                                                   outToServer
                                      output                                        input
   An output stream is               stream                                       stream

    attached to an output
                                              client TCP
    source, e.g., monitor or                    clientSocket
                                                socket                                 TCP
    socket.                                                                           socket

                                            to network           from network



                                                                                               22
   Socket programming with TCP

Example client-server app:
1) client reads line from standard input (inFromUser
   stream) , sends to server via socket (outToServer
   stream)
2) server reads line from socket
3) server converts line to uppercase, sends back to client
4) client reads, prints modified line from socket
   (inFromServer stream)




                                                             23
            Example: Java client (TCP)
                     import java.io.*;
                     import java.net.*;
                     class TCPClient {

                       public static void main(String argv[]) throws Exception
                       {
                         String sentence;
                         String modifiedSentence;
            Create
      input stream        BufferedReader inFromUser =
                           new BufferedReader(new InputStreamReader(System.in));
           Create
    client socket,        Socket clientSocket = new Socket("hostname", 6789);
 connect to server
            Create        DataOutputStream outToServer =
     output stream         new DataOutputStream(clientSocket.getOutputStream());
attached to socket

                                                                                 24
   Example: Java client (TCP), cont.

            Create            BufferedReader inFromServer =
      input stream             new BufferedReader(new
attached to socket             InputStreamReader(clientSocket.getInputStream()));

                              sentence = inFromUser.readLine();
          Send line
          to server           outToServer.writeBytes(sentence + '\n');

          Read line           modifiedSentence = inFromServer.readLine();
       from server
                              System.out.println("FROM SERVER: " + modifiedSentence);

                              clientSocket.close();

                          }
                      }
                                                                                    25
         Example: Java server (TCP)
                      import java.io.*;
                      import java.net.*;

                      class TCPServer {

                       public static void main(String argv[]) throws Exception
                        {
                          String clientSentence;
           Create         String capitalizedSentence;
 welcoming socket
                          ServerSocket welcomeSocket = new ServerSocket(6789);
     at port 6789
                          while(true) {
Wait, on welcoming
socket for contact            Socket connectionSocket = welcomeSocket.accept();
          by client
                             BufferedReader inFromClient =
     Create input             new BufferedReader(new
stream, attached              InputStreamReader(connectionSocket.getInputStream()));
        to socket

                                                                                   26
   Example: Java server (TCP), cont

   Create output
stream, attached           DataOutputStream outToClient =
       to socket            new DataOutputStream(connectionSocket.getOutputStream());
    Read in line
    from socket            clientSentence = inFromClient.readLine();

                           capitalizedSentence = clientSentence.toUpperCase() + '\n';
  Write out line
                           outToClient.writeBytes(capitalizedSentence);
      to socket
                       }
                   }
              }                  End of while loop,
                                 loop back and wait for
                                 another client connection



                                                                                        27
 Socket programming with UDP

UDP: no “connection” between
  client and server
 no handshaking
 sender explicitly attaches IP    application viewpoint
  address and port of              UDP provides unreliable transfer
  destination to each packet       of groups of bytes (“datagrams”)
 server must extract IP               between client and server
  address, port of sender from
  received packet
UDP: transmitted data may be
  received out of order, or lost




                                                                  28
 Client/server socket interaction: UDP
Server (running on hostid)   Client

     create socket,          create socket,
     port=x, for             clientSocket =
     incoming request:       DatagramSocket()
     serverSocket =
     DatagramSocket()
                             Create, address (hostid, port=x,
                             send datagram request
                             using clientSocket
      read request from
      serverSocket

      write reply to
      serverSocket
      specifying client        read reply from
      host address,            clientSocket
      port number              close
                               clientSocket




                                                                29
Example: Java client (UDP)
                          keyboard           monitor




                                inFromUser
                        input
                       stream


            Client
            Process
                                                                            Input: receives
            process
                                                                            packet (recall
Output: sends                                                               thatTCP received
packet (recall                                                              “byte stream”)




                                                receivePacket
                                sendPacket
that TCP sent          UDP
                      packet
                                                                 UDP
                                                                packet
“byte stream”)
                               client UDP
                                 clientSocket
                                 socket                             UDP
                                                                   socket

                          to network         from network




                                                                                               30
            Example: Java client (UDP)
                      import java.io.*;
                      import java.net.*;

                      class UDPClient {
                         public static void main(String args[]) throws Exception
                         {
            Create
      input stream        BufferedReader inFromUser =
                           new BufferedReader(new InputStreamReader(System.in));
            Create
      client socket       DatagramSocket clientSocket = new DatagramSocket();
         Translate
                          InetAddress IPAddress = InetAddress.getByName("hostname");
   hostname to IP
address using DNS         byte[] sendData = new byte[1024];
                          byte[] receiveData = new byte[1024];

                          String sentence = inFromUser.readLine();
                          sendData = sentence.getBytes();
                                                                                       31
      Example: Java client (UDP), cont.
    Create datagram
  with data-to-send,     DatagramPacket sendPacket =
length, IP addr, port     new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

    Send datagram        clientSocket.send(sendPacket);
         to server
                         DatagramPacket receivePacket =
                          new DatagramPacket(receiveData, receiveData.length);
    Read datagram
                         clientSocket.receive(receivePacket);
      from server
                         String modifiedSentence =
                            new String(receivePacket.getData());

                         System.out.println("FROM SERVER:" + modifiedSentence);
                         clientSocket.close();
                         }
                     }


                                                                                     32
        Example: Java server (UDP)
                     import java.io.*;
                     import java.net.*;

                     class UDPServer {
                      public static void main(String args[]) throws Exception
          Create        {
 datagram socket
                         DatagramSocket serverSocket = new DatagramSocket(9876);
    at port 9876
                         byte[] receiveData = new byte[1024];
                         byte[] sendData = new byte[1024];

                         while(true)
                          {
  Create space for
                           DatagramPacket receivePacket =
received datagram
                            new DatagramPacket(receiveData, receiveData.length);
           Receive          serverSocket.receive(receivePacket);
         datagram
                                                                                   33
    Example: Java server (UDP), cont
                            String sentence = new String(receivePacket.getData());
      Get IP addr
                            InetAddress IPAddress = receivePacket.getAddress();
       port #, of
           sender           int port = receivePacket.getPort();

                                   String capitalizedSentence = sentence.toUpperCase();

                            sendData = capitalizedSentence.getBytes();
Create datagram
                            DatagramPacket sendPacket =
to send to client            new DatagramPacket(sendData, sendData.length, IPAddress,
                                       port);
      Write out
       datagram             serverSocket.send(sendPacket);
       to socket        }
                    }
                }                    End of while loop,
                                     loop back and wait for
                                     another datagram
                                                                                          34

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:4
posted:10/1/2011
language:English
pages:34