Net CECS 327
Popular in Course
Popular in Computer Science and Engineering
This 207 page Class Notes was uploaded by Zackary Cronin on Monday October 5, 2015. The Class Notes belongs to CECS 327 at California State University - Long Beach taught by Jeho Park in Fall. Since its upload, it has received 26 views. For similar materials see /class/218750/cecs-327-california-state-university-long-beach in Computer Science and Engineering at California State University - Long Beach.
Reviews for Net
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/05/15
CECS 327 Netcentric Computing Distributed Computing Paradigms Instructor Dr Jeho Park California State University Long Beach Previously SynchronousAsynchronous Event Diagram Sequence Diagram Data representation Data marshalling O Flattening serializing and converting encoding Overview of Ch 3 0 In this chapter we will look at the classi cation of the paradigms for distributed computing applications Paradigms and Abstraction Paradigm means a pattern example or model 0 Characteristics that distinguish distributed applications from conventional singlemachine applications Interprocess communication A distributed application require the participation of two or more independent entities processes To do so the processes must have the ability to exchange data among themselves Event synchronization In a distributed application the sending and receiving of data among the participants of a distributed application must be synchronized Abstractions O Abstraction is the idea of detail hiding 0 To quote David J Barnes39 We often use abstraction when it is not necessary to know the exact details of how something works or is represented because we can still make use of it in its simpli ed form Getting involved with the detail often tends to obscure what we are trying to understand rather than illuminate it Abstraction plays a very important role in programming because we often want to model in software simpli ed versions of things that exist in the real world without having to build the real things 0 ln software engineering abstraction is realized with the provision of tools or facilities which allow software to be built without the developer having to be cognizant of some of the underlying complexities Distributed computing paradigms and their level of abstraction level of abstraction high object space Collaborative apps network services object request broker mobile agent remote procedure call remote method invocation clientserver peertopeer message passing The Message Passing Paradigm Message passing is the most fundamental paradigm for distributed applications 0 A process sender sends a message representing a request 0 The message is delivered to a receiver which processes the request and sends a message in response In turn the reply may trigger a further request which leads to a subsequent reply and so forth Process A Process B ll a message The Message Passing Paradigm 2 The basic operations required to support the basic message passing paradigm are and For connectionoriented communication the operations SandEare also required With the abstraction provided by this model the interconnected processes perform input and output to each other in a manner similar to le lO The socket application programming interface is based on this paradigm Socke rs process sends receives host or messages To from i rs 50 C ke l39 H quot controlled by app developer 0 socke r analogous To door oz sending process shoves message ouT door buffers 391 buffers oz sending process relies on Variables variables Transpor r infras rruc rure on oTher side of door which brings message To sockeT aT receiving process controlled by OS Reference Computing Networking by Kurose and Ross The ClientServer Paradigm l o The best known paradigm for network applications 0 The clientserver model assigns asymmetric roles to two collaborating processes one process the server plays the role of a service provider which m passively for the arrival of requests The other the client issues specific requests to the server and awaits its response service request C a client process 3 a server process Server host 0 a SGfVice Client host The ClientServer Paradigm 2 0 Simple in concept the clientserver model provides an efficient abstraction for the delivery of network services Operations required A server process listen and accept requests A client process issue requests and accept responses Many Internet services are clientserver applications These services are often known by the protocol that the application implements Well known Internet services include HTTP FTP DNS finger gopher etc HTTP CIien r Server Model HTTP hyper rex r Transfer pro rocol p Web39s opplico rion layer proTocol PC running H7 Explorer p clien rserver model oz ciem browser ThoT requesTs receives running quotdisplaysquot Web objec rs Apache Web SCPVCIquot oz server Web server sends objec rs in Mac running response To requesTs Nav39gafor Reference Computing Networking by Kurose and Ross The PeertoPeer Paradigm l 0 In system architecture and networks peertopeer is an architecture where computer resources and services are direct exchanged between computer systems These resources and services include the exchange of information processing cycles cache storage and disk storage for les In such an architecture computers that have traditionally been used solely as clients communicate directly among themselves and can act as both clients and servers assuming whatever role is most ef cient for the network The PeertoPeer Paradigm 2 In the peer to peer paradigm the participating processes play equal roles with equivalent capabilities and responsibilities hence the term peer Each participant may issue a request to another participant and receive a response process 1 A reques request r espouse V process 2 The PeertoPeer Paradigm 3 Client server paradigm ideal model for a centralized network service The peer to peer paradigm more appropriate for instant messaqinq Deer to Deer le transfers video conferencing and collaborative work It is also possible for an application to be based on both the client server model and the peer to peer model A well known example of a peer to peer le transfer service is Napstercom or similar sites which allow les primarily audio les to be transmitted among computers on the Internet It makes use of a server for directory in addition to the peer to peer computing l5 Pure P2P archiTecTure 39 no always on server 39 arbi rrary end sys rems direc rly communica re PeerPee 39 peers are in rermi r ren rly connec red and change IP addresses Reference Computing Networking by Kurose and Ross P2P cen rrolized index original Nops rer design cemahzed 1 when peer connec rs i r diredrserverM l informs cen rrol server quotI 7 oz IP address oz con ren r 2 Alice queries for Hey J udequot 3 Alice reques rs file from Bob Reference Computing Networking by Kurose and Ross P2P problems wi rh cen rrolized direc rory single poin r of failure file Transfer is performance bo r rleneck decen fr alized bu f loco ring con ren r is co ri h r infrin emen r W 9 9 highly cen rrolized rorge rquot of lowsui r is obvious Reference Computing Networking by Kurose and Ross File dis rribu rion Bi rTorren r p P2P file dis rr39ibu rion fracker39 Tracks peers M group of pariiciia ring in Torrent Peers eXChang39 9 chunks of a file obTain sf of peers Trading 4 ch u nks Reference Computing Networking by Kurose and Ross BiTTor39r39enT g1 file divided in l39o 256KB chunks peer joining 139or r en1quot has no chunks but will accumula I39e 139 over39 139ime r39egis139er39s wi I39h 139r39acker39 To get list of peers connec I39s To Subset of peers neighbor39s while downloading peer uploads chunks 139o o139her39 peer39s peer39s may come and go once peer has en l39ir39e file if may selfishly leave or al l39r39uis139ically r39emain Reference Computing Networking by Kurose and Ross The future at peerto peer The ieBh ap39ping technology popuianzad by Napat lr Innnwn as pear Wp39aar nohmlking m Inme to d mnga haw amine and mrpom ona UM the Warns1 Instead of relying an centre senera to process and relay quot 39 39 Haw rrquot u ming dwnlop r39rd wfl ailiow umr Io Tum device mm a 59mm 31 pui ng A Virtual Inserting room Users mm m U Inmme39t wasng a prugram than rodc5 Irka an online chat room A la is placedzi his a quotshamd space withn the vinual masking team which all2mm nears to 39N39Ork on data fie 19 an 19 same lime Usema mode in real Emma and can inst 1n message each other in than Iutu a this fright be dune Ihluu h davioes aum hawtibial E and cell WW5 Whal is an thn maroon Namns c Milne imam FMn Ehal n bun1g wowed on Irishm r V quot10555ng 1 l lm a 1 Jm fr ma wpuw H M 1 jLWS armu Niamuxnnw rnmnkl kam AP an Human 2 JLP anpw Classful vackAddress Scheme In lP version 4 each address is 32 bit long The address space accommodates 232 43 billion addresses in total Addresses are divided into 5 classes A through E Byte 0 Byte 1 Byte 2 Byte 3 Class A Network Host 16777215 hosts Class B 0 Network HOS C 65555 hosts Class C 1 Network I H08 255 hostsnetwork 1 1 Multicast group Reserved Multicast Reserved IP Addressing An IP network address is assigned by an authority IANA Classful lP Addressing turned out to be inefficient Hard to accommodate future demands and plans Big gap between Class C too small and B too big IP address IPv4 shortage noticed in 1990 Possible solutions lP Subnetting for better hierarchy Dynamic address assignment IPv6 128 bits long 3x1038 1000 IP addressm2 on the surface of the Earth land and sea NAT Network Address Translation IP Subnetting Subnetting is used to break the network into smaller more efficient subnets to prevent excessive rates of Ethernet packet collision and excessive routing table growth in a large network IP Subnetting 1341396016 10000110 10001011 00111100 00010000 2Ievel Network ID Host ID 10000110100010110011110000010000 11111111111111111111111110000000 3Ievel Network ID Subnet ID Host ID Subnet Mask 255255255 I28 The Domain Name System For user friendliness each Internet address is mapped to a symbolic name using the DNS in the format of ltComputer namegtltsubdomain hierarchygtltorganizationgtltsector namegtltcountry codegt eg wwwcecscsubedu toplevel domain 4 0 0 7 US in the organization Toplevel domain name has to be applied i or Subdomain hierachy and names are ass1gned by the organization subdomain O QC host name i The Domain Name System For network applications a domain name must be mapped to its corresponding Internet address Processes known as DNS servers provide the mapping service based on a distributed database of the mapping scheme The mapping service is offered by thousands of DNS servers on the Internet each responsible for a portion of the name space called a zone The servers that have access to the DNS information zone file for a zone is said to have authority for that zone Addressing a Process on a Host Each host has 65536 ports Well Known Ports 0 Each Internet host has 216 6553 5 logical ports Each port is identi ed by a number between 1 and 65 5 35 and can be allocated to a particular process 0 Port numbers between 1 and 1023 are reserved for processes which provide wellknown services such as nger FTP HTTP and email Assignment of some wellknown ports Protocol Port Service echo 7 IPC testing daytime 13 provides the current date and time ftp 21 le transfer protocol telnet 23 remote commandline terminal session smtp 25 simple mail transfer protocol time 37 provides a standard time nger 79 provides information about a user http 80 web server RMI Registry registry for Remote Method Invocation web sener which supports servlets JSP orASP special web server Choosing a Port For our programming exercises when a port is needed Choose a random number above the well known ports 1024 65535 Network Basics Protocols 0 Network Architecture OSI Sevenlayer Network Architecture 0 Internet Fourlayer Network Architecture 0 Application layer Transport layer Internet Layer Physical layer TCPIP Suite IPv4 Address Scheme 0 Domain Name System Service Operating systems review Process and Thread Processes are runtime representations of programs A process consists of an executing program executable code its current values state information the resources used by the operating system to manage its execution at least one thread of execution Each process provides the resources needed to execute a program Operating systems review Process and Thread A thread is the entity within a process that can be scheduled for execution All threads of a process share its virtual address space and system resources Each process is started with a single thread but can create additional threads from any of its threads Threads are distinguished from processes in that processes are typically independent while threads subsets of a process processes carry considerable state information where multiple threads within a process share state as well as memory and other resources processes have separate address spaces where threads share their address space processes interact only through systemprovided inter process communication mechanisms context switching between threads in the same process is typically faster than context switching between processes source Wikipedia Process State Transition Diagram event completion blocked Simplifed finite state diagram for a process39s lifetime for event Three Types of Java Program Applications applets and servlets A Java application program has a main method and is run as an independentstandaone process may run as monolithic or as distributed program An applet does not have a main method and is run using a browser s JVM or the appletviewer A servlet does not have a main method and is run in the context of a web server at the request of a browser A Java program is compiled into bytecode a universal object code When run the bytecode is interpreted by the Java Virtual Machine JVM A standalone Java application is run on a local machine computer Java object 0 Java Virtual Machine An applet is an object downloaded transferred from a remote machine then run on a local machine an applet Java object O Java Virtual Machine A servlet is an object that runs on a remote machine and interacts with a local program using a requestresponse protocol a ser et request a process Ca 0 response WWWWWWWWWWWWWWWWWW77WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW A sample of a simple Java application M Liu 1802 import javaio class MyProgram public static void mainString args throws IOException BufferedReader keyboard new BufferedReadernew InputStreamReaderSystemin String theName SystemoutprintlnquotWhat is your namequot theName keyboardreadLine SystemoutprintquotHello quot theName Systemoutprintlnquot welcome to CSC369nquot end main end class l A sample of a simple applet M Liu 1802 I import javaappletApplet import javaawt public class MyApplet extends Applet public void paintGraphics g setBackgroundColorblue Font Claude new FontquotArialquot FontBOLD 40 gsetFontClaude gsetColorColoryellow gdrawStringquotHello Worldquot 100 100 end paint end class lt A web page which when browsed will run gt lt the MyApplet appletgt lt M Liu 1802gt lttitlegtSampleAppletltltitlegt lthrgt ltapplet codequotMyAppletclassquot width500 height500gt ltappletgt lthrgt lta hrefquotHellojavaquotgt39Ihe sourceltagt A sample of a simple Java servlet M Liu 1802 I import javaio import javatext import javautil import javaxservlet import javaxservlethttp public class MyServlet extends HttpServlet public void doGet HttpServletRequest request HttpServletResponse response throws ServletException IOException PrintWriter out String title quotMyServlet Outputquot set content type and other response header fields rst responsesetContentTypequottexthtmlquot then write the data of the response out responsegetWriter outprintlnquotltH39IMLgtltIIEADgtltTI39ILEgtquot outprintlntitle outprintlnquotltTI39ILEgtltHEADgtltBODYgtquot outprintlnquotltH1gtquot title quotltH1gtquot outprintlnquotltPgtHello Worldquot outprintlnquotltBODYgtltH39I MLgtquot outclose end doGet end class Concurrent Processing Timesharing Processes Timesharng of a resource Actually one process at a time Concurrent Processing within a process A parent process may spawn child processes A process may spawn child threads a rocess parent process p main thread child thread 1 h1 2 child processes 0 1 d thread Concurrent processing Within a process Java Threads Two ways to create a new threads 0 Using a subclass of the Thread Class 0 Using a Class that implements the Runnable interface Java Threads Using a subclass of the Thread Class import SomeThread public class RunThreads public static void main String args SomeThread p1 new SomeThread1 p1start SomeThread p2 new SomeThread 2 p2start SomeThread p3 new SomeThread 3 p3start 0 end class RunThreads public class SomeThread extends Thread int myID SomeThreadint id thismyID id public void run int i for i 1 ilt 11 i System0utprintln quotThreadquotmyID quot quot i end class SomeThread Java Threads Using a Class that implements the Runnable interface public class RunThreads2 public static void main String args Thread p1 new Threadnew SomeThread21 p1start Thread p2 new Threadnew SomeThread22 p2start Thread p3 new Threadnew SomeThread23 p3start class SomeThreadZ implements Runnable int myID SomeThread2int id thismyID id public void run int i for i 1 ilt 11 i System0utprintln quotThreadquotmyID quot quot i end class SomeThread Threadsafe Programming When two threads independently access and update the same data object the updating needs to be synchronized Race condition I fetch value in counter and load into a register I fetch value in counter and load into a register I I increment value in register I fetch value in counter and load into a register I I store value in register to counter I increment value in register I I I increment value in register I I fetch value in counter and load into a register I increment value in register I store value in register to counter I store value in register to counter store value in registerto counter This execution results in the This execution results in the value 2 in the counter value 1 in the counter ll instruction executed in concurrent process or thread 1 E instruction executed in concurrent process or thread 2 Synchronized Method class SomeThread3 implements Runnable static int count0 SomeThread3C superCD public void run updateC static public synchronized void updateC int myCount count int second intMathrandom 500 try Threadsleepsecond catch InterruptedException e myCount count myCount Systemoutprintlnquotcountquotcountquot thread countquot ThreadactiveCount D end class SomeThread3 import SomeThread3 public class RunThreads3 public static void main String args int originalThreadCount ThreadactiveCount for int i0 ilt10 i Thread p new Threaanew SomeThread3 pstart Systemoutprintlnquotthread countquot ThreadactiveCount D while ThreadactiveCount gt originalThreadCount loop until all child threads have exited SystemoutprintlnquotFinally Count quot SomeThread3count end class RunThreads3 CECSSZ7 Spring 2009 The Client Server Paradigm 4 Instructor Dr Jeho Park Daytime Protocol Implementation Connectionoriented Daytime ClientServer Sample 2 using connectionoriented sockets DaytimeClient2java Presentation Logic DaytimeClientHelper2java Application Logic MyStreamSocketjava Service Logic stream mode socket no need to send a null message DaytimeServer2java no need to read a request it is implicit UML Diagram for stream mode DaytimeCient2 presentation layer DaytimeClient2 l DaytimeClientHelperZ MyStre amSocket Socket sendMessageO receiveMessageO application logic layer service layer UML Diagram for stream mode DaytimeServer2 ServerSocket presentation application logic layer of DnytimeServerz MyStreamSocket Socket setStreams sendMessage recevieMessage service layer Testing a Network Service Because of its inherent complexity network software is notoriously difficult to test Use the threelayered software architecture and modularize each layer on both the client and the server sides Use an incremental or stepwise approach in developing each module Starting with stubs for each method compile and test a module each time after you put in additional details Develop the client first It is sometimes useful to employ an Echo server to be introduced in the next section which is known to be correct and which uses a compatible IPC mechanism to test the client independent of the server doing so allows you to develop the client independent of the server Use diagnostic messages throughout each program to report the progress of the program during runtime Test the clientserver suite on one machine before running the programs on separate machine Connectionless server vs connectionoriented server Connectionless vs connection oriented server A connectionless server Uses a connectionless IPC API eg connectionless datagram socket Sessions with concurrent clients can be interleaved A connectionoriented server Uses a connection oriented IPC API eg stream mode socket Sessions with concurrent clients can only be sequential unless the server is threaded EchoServer1connectionless Excerpt public class EchoServerl public static void mainCStringE args instantiates a datagram socket For both sending and receiving data MyServerDatagramSocket mySocket new MyServerDatagramSocketCserverPort while true Forever loop DatagramMessage request mySocketreceiveMessageAndSenderC String message requestgetMessage mySocketsendMessageCrequestgetAddress requestgetPort message end while Concurrent client sessions with EchoServer1 EchoServer1 EchoClient1 A EchoClient1 B rnessage 39 I echo message echo message message echo message echo I I I I I I I I i I I echo i I I I I I I I I I I EchoServer2 Connectionoriented excerpt ServerSocket myConnectionSocket new ServerSocketCserverPort while true Forever loop MyStreamSocket myDataSocket new MyStreamSocket myConnectionSocketacceptC boolean done False while done message myDataSocketreceiveMessage iF messagetrimequals endMessage myDataSocketclose done true end iF else myDataSocketsendMessageCmessage end else end while done end while Forever Two consecutive client sessions with echo server2 EchoServer2 EchoCIient2 A EchoCIient2 B message I 1 i J echo no interleaving message echo echo message echo message I I I echo r I I I I I I I I I I I I I rnessage I I I I I I I I I I I I Iterative servers Vs Concurrent servers Concurrent Server 0 A connection oriented server can be threaded so that it can service multiple clients concurrently Such a server is said to be a concurrent server 0 An unthreaded connection oriented server is said to be an iterative server A Concurrent Connection oriented Server A client process at the head of the connection queue server host concurrert server process 5 k the server connection queue e 39n e 39n the main thread accepts39c39onnections T a child thread processes i the protocol for a A chent process Whose connectlon has been accepted client process A client process whose connection has been accepted Sequence diagram EchoServer3 glnld 5 m r 1 pue wmm wow B me Q m n B a l l l l l l l l l l l l l l l l lur l l l l l l llxnll O m E A WW n B l l l l l l l l l l l l l lllllllll l NM x m C 8 IE m e llll mlllllllxll llll S N N lt lt I I I I I I I I I I I I I I I I I I II S e m ll l l l l l l l l l l l l l l l l l l l l l l l l ll 8 O m E EchoSenerS concurrent excerpt ServerSocket myConnectionSocket new ServerSocketCserverPort while true forever loop MyStreamSocket myDataSocket new MyStreamSocketCmyConnectionSocketacceptC D Thread theThread new Threaanew ServerThreadeyDataSocket theThreadstart end while forever SenerThreadjava excerpt class ServerThread implements Runnable static Final String endMessage quotquot MyStreamSocket myDataSocket EchoServerThreadCMyStreamSocket myDataSocket thismyDataSocket myDataSocket public void run boolean done False String message try put in here the logic For each client session while done message myDataSocketreceiveMessageC iF messagetrimequals endMessage myDataSocketclose done true end if else myDataSocketsendMessageCmessage end else end while done end try catch Exception ex end run end class Server Thread Class template class ServerThread implements Runnable static Final String endMessage quotquot MyStreamSocket myDataSocket ServerThreadCMyStreamSocket myDataSocket thismyDataSocket myDataSocket public void run boolean done False String message try add code here end try catch Exception ex SystemoutprintlnquotException caught in thread ex end run end class anpw Three Types of Java Program Applications applets and servlets A Java application program has a main method and runs as an independentstandaone process may run as monolithic or as distributed program An applet does not have a main method and runs using a browser s JVM or the appletviewer A servlet does not have a main method and runs in the context of a web server at the request of a browser A Java program is compiled into bytecode a universal object code When run the bytecode is interpreted by the Java Virtual Machine JVM A standalone Java application is run on a local machine computer Java object 0 Java Virtual Machine An applet is an object downloaded transferred from a remote machine then run on a local machine an applet Java object O Java Virtual Machine A servlet is an object that runs on a remote machine and interacts with a local program using a requestresponse protocol a ser et request a process Ca 0 response WWWWWWWWWWWWWWWWWW77WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW A sample of a simple Java application M Liu 1802 import javaio class MyProgram public static void mainString args throws IOException BufferedReader keyboard new BufferedReadernew InputStreamReaderSystemin String theName SystemoutprintlnquotWhat is your namequot theName keyboardreadLine SystemoutprintquotHello quot theName Systemoutprintlnquot welcome to CSC369nquot end main end class l A sample of a simple applet M Liu 1802 I import javaappletApplet import javaawt public class MyApplet extends Applet public void paintGraphics g setBackgroundColorblue Font Claude new FontquotArialquot FontBOLD 40 gsetFontClaude gsetColorColoryellow gdrawStringquotHello Worldquot 100 100 end paint end class lt A web page which when browsed will run gt lt the MyApplet appletgt lt M Liu 1802gt lttitlegtSampleAppletltltitlegt lthrgt ltapplet codequotMyAppletclassquot width500 height500gt ltappletgt lthrgt lta hrefquotHellojavaquotgt39Ihe sourceltagt trx A sample of a simple Java servlet M Liu 1802 I import javaio import javatext import javautil import javaxservlet import javaxservlethttp public class MyServlet extends HttpServlet public void doGet HttpServletRequest request HttpServletResponse response throws ServletException IOException PrintWriter out String title quotMyServlet Outputquot set content type and other response header fields rst responsesetContentTypequottexthtmlquot then write the data of the response out responsegetWriter outprintlnquotltH39IMLgtltIIEADgtltTI39ILEgtquot outprintlntitle outprintlnquotltTI39ILEgtltHEADgtltBODYgtquot outprintlnquotltH1gtquot title quotltH1gtquot outprintlnquotltPgtHello Worldquot outprintlnquotltBODYgtltH39I MLgtquot outclose end doGet end class Concurrent Processing Timesharing Processes Timesharng of a resource Actually one process at a time Concurrent Processing within a process A parent process may spawn child processes A process may spawn child threads a rocess parent process p main thread h39l hr 2 child processes 0 1 dt ead Concurrent processing within a process Multithreading has several advantages over Multi processing such as Threads are lightweight compared to processes Threads share the same address space and therefore can share both data and code Context switching between threads is usually less expensive than between processes Cost of thread intercommunication is relatively lower than that of process intercommunication Java Threads 0 The Java Virtual Machine allows an application to have multiple threads of execution running concurrently A Java Virtual Machine starts up with a single thread The Java Virtual Machine continues to execute threads until either of the following occurs The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place All threads have terminated either by returning from the call to the run method or by throwing an exception that propagates beyond the run method 0 Java provides a Thread class public class Thread implements Runnable Java Threads Two ways to create a new thread 0 Using a subclass of the Thread Class 0 Using a Class that implements the Runnable interface Java Threads Using a subclass of the Thread Class import SomeThread public class RunThreads public static void main String args SomeThread p1 new SomeThread1 p1start SomeThread p2 new SomeThread 2 p2start SomeThread p3 new SomeThread 3 p3start 0 end class RunThreads public class SomeThread extends Thread int myID SomeThreadint id thismyID id public void run int i for i 1 ilt 11 i System0utprintln quotThreadquotmyID quot quot i end class SomeThread Java Threads Using a Class that implements the Runnable interface public class RunThreads2 public static void main String args Thread p1 new Threadnew SomeThread21 p1start Thread p2 new Threadnew SomeThread22 p2start Thread p3 new Threadnew SomeThread23 p3start class SomeThreadZ implements Runnable int myID SomeThread2int id thismyID id public void run int i for i 1 ilt 11 i System0utprintln quotThreadquotmyID quot quot i end class SomeThread Threadsafe Programming When two threads independently access and update the same data object the updating needs to be synchronized If it s not synch the program may end up having race condition Race condition time I fetch value in counter and load into a register I I fetch value in counter and load into a register I I increment value in register I I fetch value in counter and load into a register I I store value in register to counter I I increment value in register I increment value in re ister I fetch value In counter and load Into a register I I g I I increment value in register I store value in register to counter I store value in register to counter I store value in registerto counter This execution results in the This execution results in the value 2 in the counter value 1 in the counter ll instruction executed in concurrent process or thread 1 E instruction executed in concurrent process or thread 2 Mghgam mit Q39anp u SSS 39 ations Ir ctorz Dr Jeho Park What is IPC IPC or Inter Process Communication is a capability that allows one process to communicate with another process The processes can be running on the same computer or on different computers connected through a network What are the primitive operations an IPC API provides Send destination and data Receive source and data storage Connect for connectionoriented IPC connect and accept Disconnect for connectionoriented IPC connection deallocation Event Synchronization Web Browser connect to a Web server send a request to the Web server receive data sent from the Web server disconnect process data Web Server acceptconnec on receive request process the request received send the data requested BlockingNonblocking SynchronousAsynchronous Operations SSSR O Process2 Process 0 ASAR lblocking rec ive starts nonblo ckin operation gt execution ow 7 suspended period blocking rece ve returns Asynchronous Send and Synchronous Receive Event Diagram Web Server Web Browser Interprocess communication 4 Execution flow response Process blocked Sequence Diagram Web Server Web Browser I Time lt Message H39ITP request Execution flow H39ITP response V I I I I lt I I I I I I I I I I I For a sequence diagram we focus on actual message flow when what and from where to where Internet Applications 2 Instructor Dr Jeho Park Characteristics of H39ITP HTTP is a ConnectionOriented Protocol 0 With HTTP10 a connection to a server is automatically closed as soon as the server returns a response Thus exactly one round of exchange is allowed between a client and a web server if a client needs to contact the same server in one browser session it must reconnect to the server to reissue another request HTTP is a ConnectionOriented Protocol 0 H39ITP10 was extended to allow a request header line Connection KeepAlive to be issued by a client who wishes to maintain a persistent connection with the server a cooperating server will keep the connection open after sending a response 0 Server response with Connection KeepAlive Keep Alive timeout10 max5 optional 0 ln H39l39l39Pt 1 connections are persistent by default Such a connection allows multiple requests to be send over the same TCP connection HTTP is a stateless Protocol HTTP 10 as well as version 11 is also a stateless protocol the server does not maintain any state information on a client s session Regardless of whether the connection is kept alive each request is handled by a server as a new request Dynamically generated web contents O In the beginning H39ITP was employed to transfer static contents that is contents that exist in a constant state such as a plain text file or an image file 0 A typical web application such as a shopping cart requires fetching remote data based on data entered by a client at runtime dynamically O A generic H39ITP server does not possess the application logic for fetching the data from the data source Dynamically generated web contents 0 Instead an external process that has the application logic will serve as an intermediary The external process runs on the server host accepts input data from the web server exercises its application logic to obtain data from the data source returns the outcome to the web server which transmits the outcome to the client Dynamically generated web contents 0 The first widely adopted protocol to augment HTTP in supporting runtime generated web contents is the Common Gateway Interface CGI protocol 0 Although rudimentary by comparison CGI is the predecessor of more sophisticated protocols and facilities such the Java Servlet that serve similar purpose The understanding of CGI and some of its supplementary protocols is important in that it prepares us for the understanding of more advanced protocols and facilities 8 Common Gateway Interface CGI O The Common Gateway Interface CGI is a standard for providing an interface or a gateway between an information server and an external process that is a process external to the server Using the protocol a web client may specify a program known as a CGI script as the target web object in an HTTP request The web server fetches the CGI script activates it as a process passing to the process input data transmitted by the web client The web script executes and transmits its output to the web server which returns the webscript generated data as the body of a response to the web client 9 CGI2 0 An H39ITP request may specify a CGI program or CGI script 0 A CGI program can be written in 0 Programming languages C Ada C Fortran such a program needs to be compiled to generate an executable Script languages such as Perl such a program referred to as a CGI script requires the appropriate language interpreter to be present at the server host 0 CGI is commonly used for processing user input from HTML forms and subsequently composing a web page sent as part of the server response I0 CGI Program 3 0 When a web server receives a request whose URI specifies a web program the web server initiates the execution of the web program 0 The web program formulates its output in HTML which is sent to the server and forwarded to the web client as the HTTP response Action field in a web page A web script can be specified in an action field of a web page When the web page is submitted an H39ITP request is issued by the browser specifying the web script as the URI ltHTMLgt ltHEADgt ltTTLEgtA Simple Web Page which illustrates CGltTITLEgt ltHEADgt ltBODYgt ltFORM ACTIONquotHelocgiquotgt ltCENTERgt Click on the SUBMIT button to activate the CGI script Hellocgiltbrgt ltNPUT TYPEquotSubmitquot NAMEquotsubmitquot VALUEquotSUBMITquotgt ltCENTERgt ltFORMgt Common Gateway Interface CGI Web server host web client host CGI script HTTP server web client request for hellohtml contents of hellohtm1 request for hellocgi Adata if any from the client HTTP server response includingl dynamically generated web page I3 A sample web script hellop usr10calbinper1 simple Perl CGI script quotContent type texthtm1nnquot quotltheadgtnquot quotlttit1egtHe110 Wor1dlttit1egtnquot quotltheadgtnquot quotltbodygtnquot quotltFont color b1uegtnquot quotlthlgtHe110 Wor1dlthlgtnquot quotltFontgtnquot quotltbodygtnquot A Web Form Query String 0 An example of a query string for the example form is nameJohn20Doeampquestpeace200n 20earthampcoorazureampswalowcontinentaamptextTh e20return20is203E1725 all on one line 0 The collection of the data into a query string including the encoding of the values is performed by the browser When the form is submitted by the user the query string is passed to the server in the HTTP request in a manner depending on the FORM METHOD specified in the form The query string is then forwarded by the server to the external program l5 BS ons 2 ctorz Dr Jeho Park Previously 0 OS basics 2 0 Processes and Threads 0 Java programs three types 0 Race condition and mutual exclusion 0 Java thread programming 0 Threadsafe programming usingJava monitor Java Monitor monitor building Synchronized Method class SomeThread3 implements Runnable static int count0 SomeThread3C superCD public void run updateC static public synchronized void updateC int myCount count int second intMathrandom 500 try Threadsleepsecond catch InterruptedException e Systemourprintln INT Exception myCount count myCount Systemoutprintlnquotcountquotcountquot thread countquot ThreadactiveCount D end class SomeThread3 import SomeThread3 public class RunThreads3 public static void main String args int originalThreadCount ThreadactiveCount for int i0 ilt10 i Thread p new Threaanew SomeThread3 pstart Systemoutprintlnquotthread countquot ThreadactiveCount D while ThreadactiveCount gt originalThreadCount loop until all child threads have exited SystemoutprintlnquotFinally Count quot SomeThread3count end class RunThreads3 thread count2 thread count3 thread count4 thread count5 count1 thread thread count5 thread count6 thread count7 thread count8 thread count9 thread count1 count2 thread count1 count3 count4 count5 count6 count7 count8 count9 count10 thread count2 thread thread thread thread thread thread thread count9 count8 count7 count6 count5 count4 count3 finally Count 10 thread thread thread thread thread thread count1 thread thread thread thread thread count2 count3 count4 count5 count6 count7 count7 count8 count9 count1 count2 thread count1 count1 count2 count1 count1 count1 count2 count1 count2 finally thread thread thread thread thread thread thread thread Count count9 count8 count7 count6 count5 count4 count3 count2 2 And previously 0 Interprocess Communication IPC 0 Basic IPC program interface 0 send receive connect disconnect 0 Event Synchronization 0 BIockingnonblocking operations 0 Event diagram and Sequence diagram Synchronous SendSynchronous Receive Process Process 2 39 Blocking receive Blocking starts send 39 39 starts Blocking send ends 39 Blocking receive ends Transparent acknowled ment provide by the IPC facility Asynchronous SendSynchronous Receive Process Process 2 39 Blocking receive Nonblocking 39 5 starts send issued No acknowledgment Block39 8 necessary rece ve But no guarantee ends of data delivery to the receiver Event Diagram Web Server Web Browser Interprocess communication 4 Execution flow response Process blocked Sequence Diagram Web Server Web Browser I Time lt Message H39ITP request Execution flow H39ITP response V I I I I lt I I I I I I I I I I I For a sequence diagram we focus on actual message flow when what and from where to where Data Representation 0 Data transmissionOIOIOOIOI IOO 0 Netcentric computing Heterogeneous 0 Need a way to safely exchange data in any type I convert data to receivers type and send 2 send data as it is receiver converts it 3 exchange data in an external representation Scheme Process Process 2 ASCII Unicode It lconvert Unicode i OOIOI transmit Scheme 2 Process I Process 2 ASCII Unicode I convert ASCII I OOIOI transmit Scheme 3 Process Process 2 ASCII Unicode convert 1 I convert ASNJ agreed externagtASN I Abstract 1 representation I 39 Syntax Notation Number 1 OOIOI OOIOI transmit Data marshalling 0 Marshalling the process of gathering data with structure like objects and transforming assembling it into a standard format before it is transmitted over a network so that the data can transcend network boundaries Unmarshalling when the data is transmitted the receiving computer converts the marshaled data back into an object Data marshalling 0 Two components to data marshalling 0 Flattening serializing the data structure 0 Converting encoding the data values to an external representation 0 An object from objectoriented programs needs special attention for transmission 0 Object serialization for the data the method the state of execution gt a binary stream Group Communication CECS327 Unicast vs Multicast sender receiver gt lt QnetgQng ggmmunigatign gr gnigagt G I H I onetOone onetOmany Multicast Multicasting is useful for applications such as groupware online conferences interactive distance learning online auction realtime replication of services for fault tolerance Multicast group 0 In an application or network service which makes use of multicasting a set of processes forms a group called a multicast group Each process in a group can send and receive message A message sent by any process in the group can be received by each participating process in the group A process may also choose to leave a multicast group 0 In an application such as online conferencing a group of processes interoperate using multicasting to exchange audio video andor text data An Archetypal Multicast API Primitive operations 0 Join This operation allows a process to join a specific multicast group A process that has joined a multicast group is a member of the group and is entitled to receive all multicast addressed to the group A process should be able to be a member of multiple multicast groups at any one time 0 Leave This operation allows a process to stop participating in a multicast group Multicast API Operations contd 0 Send This operation allows a process to send a message to all processes currently participating in a multicast group 0 Receive This operation allows a member process to receive messages sent to a multicast group Classification of multicasting mechanisms in terms of message delivery 1 Unreliable multicasting a multicast system will make a goodfaith attempt to deliver messages to each participating process but the arrival of the correct message at each process is not guaranteed In the best case the message is received by all processes In the worst case the message may be received by none In other cases the message may be received by some but not all or the messages may be received by some processes in a corrupted form Classification of multicasting mechanisms in terms of message delivery 2 Reliable multicast A multicast system which guarantees that each message is eventually delivered in a noncorrupted form to each process in the group is said to provide reliable multicast Definition each participating process receives exactly one copy of each message sent gt each process may receive the messages in any permutation of those messages gt When the order is significant further classification is need Classification of reliable multicast 1 Unordered An unordered reliable multicast system guarantees the safe delivery of each message but it provides no guarantee on the delivery order of the messages Example Processes P1 P2 and P3 have formed a multicast group Further suppose that three messages m1 m2 m3 have been sent to the group Then an unordered reliable multicast system may deliver the messages to each of the three processes in any of the 3 6 permutations ie m1 m2 m3 m1 m3 m2 m2m1m3 m2 m3 m1 ms m1 m2 ms39m239m1 Classification of reliable multicast 2 FIFO multicasting A system which guarantees that the delivery of the messages adhere to the following condition is said to provide FIFO firstinfirstout or sendorder multicast If process P sent messages mi and mj in that order then each process in the multicast group will be delivered the messages mi and mj in that order Suppose P1 sends messages m1 m2 and m3 in order then each process in the group is guaranteed to have those messages delivered in that same order m1 m2 then m3 Classification of reliable multicast 2 What about messages delivered by different 9 processes39 gt no restriction on the delivery order Example Suppose PI sends messages mu then mm while P2 sends messages m2 then m22 Then a FIFO multicast system can deliver the messages to each of the two processes in any of the following orders Classification of reliable multicast 3 Causal Order Multicast A multicast system is said to provide causalmulticast if its message delivery satisfies the following criterion If message m causes results in the occurrence of message mj then m will be delivered to each process prior to mj Messages m and mj are said to have a causal or happenbefore relationship denoted m gt mj The happenbefore relationship is transitory if mi gt rnj and rnj gt mk then mi gt rnj gt mk Causal Order Multicast example1 Example Suppose three processes P1 P2 and P3 are in a multicast group P1 sends a message In to which P2 replies with a multicast message m2 Since m2 is triggered by In the two messages share a causal relationship of m1 gt m2 Suppose the receiving of m2 in turn triggers a multicast message m3 sent by P3 that is m2 gt m3 The three messages share the causal relationship of In gt m2 gt m3 A causal order multicast message system ensures that these three messages will be delivered to each of the three processes in the order of m1 m2 m3 Causal Order Multioast example2 Example 2 Suppose PI multicasts message In to which P2 replies with a multicast message m2 and independently P3 replies to In with a multicast message m3 The three messages now share these causal relationships m1 gt m2 and m1 gt m3 A causal order multicast system can delivery these message in either of the following orders m1 m2 m3 0r m1 m3 m2 What abou m3 and m2 Not allowed Classification of reliable multicast 2 Atomic order multicast In an atomicorder multicast system all messages are guaranteed to be delivered to each participant in the exact same order Note that the delivery order does not have to be FIFO or causal but must be identical for each process Example P1 sends m1 P2 sends m2 and P3 sends m3 An atomic system will guarantee that the messages will be delivered to each process in only one of the six orders m1 m2 m3 m1 m3 m2 m2 m1 m3 m2 m3 m1 m3 m1 m2 m3 m2 m1 Atomic Multicast Example PI sends m then m2 P2 replies to m by sending m3 P3 replies to m3 by sending m4 Although atomic multicast imposes no ordering on these messages the sequence of the events dictates that PI must be delivered m before sending m2 Likewise P2 must receive m then m3 while P3 must receive m3 before m4 Hence any atomic delivery order must preserve the order m1 m3 m 4 Then what about m2 It can be interleaved with these messages in any manner Hence one of the following orders m1 m2 m3 m4m1m3 m2 m4orm1 m3 m4 m2 0 Unordered Reliable 0 FIFO 0 Causal order 0 Atomic order 00000000000000000000000 02252009 The socket API 2 Instructor Dr Jello Park CECS3271NeIcentrrc Computrng DrrmbutedCrJrrmutmg byM L Lru 1 Previously f o UDP and TCP O x z 0 Java Socket API z 0 Datagram sockets and Stream sockets Z 1 Connectionless datagram socket API 0 Know What you did last time in the lab 0 O O O 02262000 CECS327 NetoenmeComputmg Connectionoriented datagram socket APl connectionoriented communication the connection provided by this API is rudimentary and typically insuf cient for applications that require a true connection 2 Streammode sockets Which will be introduced later are more typical and more i appropriate for connectionoriented a communication 0 O 0 02262000 CECS 327 Netcentric Computing 2 Methods calls for connectionoriented datagrarn socket o If a datagrarn specifying another address is sent using o the socket anHlegaIArgtnnentExceptionw l occur I 0 If a datagrarn from another socket is sent to this socket o the data will be ignored 0 0 02262000 CECS 327 Netcentric Computing Connectionoriented Datagram Socket The connection is unilateral that is it is enforced only on one side The socket on the other side is free to send and receive data to and from other sockets unless it too commits to a connection to the other socket See Example3Sender Example3Receiver O 0 02262000 CECS 327 Netcentric Computing The Streammode Socket APT 39 The datagram socket APT supports the exchange of discrete units of data that is datagrams 39 39 The stream socket APT provides a model of data transfer based on the stream mode 10 of the Unix operating systems 39 By de nition a streammode socket supports connectionoriented communication only O 0 02262000 CECS 327 Netcentric Computing Streammode Socket API connectionoriented socket API O O 02262000 CECS 327 Netammo Computmg Sockets Well a lot of sockets v39 7 O O 9 Q C r w 39 7 r 0 Q r C r r Streammode Socket API 0 A streammode socket is established for data exchange between two speci c processes 39 0 Data stream is written to the socket at one end and read from the other end 0 0 A stream socket cannot be used to communicate With more than one process 0 0 02262000 CECS 327 Netcentric Computing Streammode Socket APl In Java the streammode socket API is provided with two classes ServerSocket for accepting connections we will call an object of this class a connection socket Socket for data exchange we will call an object of this class a data socket O 0 02262000 CECS 327 Netcentric Computing Streammode Socket API program ow comction listener server common Wm client mute I meaim mket Ind listen for collection reqlem me I martial tmtel l ht locket for telling lm or writing ta u mm mum gctminpltm39eul forming 0 mm 39 gemilpntmmtommg rudfmmtbutmm mmmht get In output menu for writing m m m mm 9quot dmetlethtuocht wnte to ti mam due the lat locket due ttu connection locket ante I data locket and nqlett In a mating get Ill oltput mum for writing to the min write to the them O 0 02262000 CECS 327 Netammo Computtng The server the connection listener Alumna In high an lumping whom mutterimmdhe ein O O 02262000 CECS 327 Neteentne Computng Key methods in the ServerSocket class Note Accept is ablocking operation 02262000 Key methods in the Socket class astmm connects to O Q a 02262000 CECS327NeteenmeC0mputmg 14 i Connectionoriented socket API ClientServer type server client Ed Client establish mket with remote servefs address quot 28erwrnccepts le comec onmqlest O 0 02262000 CECS 327 Netammo Compu ng Connectionoriented socket API ClientServer type 385missmrwciw operaionmingsdz 4 Sane suds xexpome using m 5Wlmthcmml hasm mimwr Cliem clam it closes sd2dl is socketwllm n usedw acneptthe protocolhl uncommon completed 0 0 02262000 CECS 327 Netammo Computmg Connectionless socket API Pl 0 Illuueu mman naiveva Mentth Inmin daugm O O 02262000 CECS 327 Netammo Computmg Example4 Em d m ommr Will humnummmmmm Immmmm mum m IIImum m quotan mmmnmwmnmmm whimMW mammal umummmrqmmmmm numwmqmmmmwmnmnn mluirnd hp Immuneimmaan 1 It llm MullahImullhmnmhmhh uhmmmmm m munmm 02262000 CECS 327 Netammo Compu ng Example4 Event Diagram ConnectionAcceptor ConnectionRequestor accept l cdnnecdonacceptance l happenedbeforethe read O attheConnechonRequestoN39 write close data socket I close connectron socket O 0 02262000 message connect request from Socket constructor 0 read close data socket CECS 327 Netcentrrc Computrng Secure Sockets httphavasuncomproductsjsse Secure sockets perform encryption on the data transmitted The JavaTM Secure Socket Extension JSSE is a Java package that enables secure Internet communications It implements a Java version of SSL Secure Sockets Layer and TLS Transport Layer Security protocols It includes anctionalities for data encryption server authentication message integrity and optional client authentication Using JSSE developers can provide for the secure passage of data between a client and a server mnning any application protocol O 0 02262000 CECS 327 Netcentric Computing 2 The Java Secure Socket Extension APl httn39iavasnn 39 39 quot quot html J J I 1 J 9 Importjavaxnetssl Class SSLServerSocket is asubclass of ServerSocket and inherits all its methods Class SSLSocket is a subclass of Socket and inherits all its methods There are also classes for Certi cation Handshaking KeyManager SSLsession O 0 02262000 CECS 327 Netcentric Computing Summary 0 In this chapter we introduced the socket application program interface for interprocess communication 39 The socket API is Widely available as a 39 programming facility for lPC at a relatively low level of abstraction O 0 02262000 CECS 327 Netcentric Computing Summary 2 39 Using the Java socket APls we introduced two types of sockets The datagram sockets which uses the User Datagram Protocol UDP at the transport layer to provide the sending and receiving of discrete data packets known as datagrams The streammode socket which uses the Tranport Layer Protocol TCP at the transport layer to provide the sending and receiving of data using a data stream 0 02262000 CECS 327 Netcentric Computing Summary 3 Key points of the Java datagram socket API 39 It supports both connectionless communication and connectionoriented communication 39 Each process must create a DatagramSocket object to sendreceive datagrams 39 39 Each datagram is encapsulated in a DatagramPacketobject O 0 02262000 CECS 327 Netcentric Computing Summary 4 a Key points of the Java datagrarn socket API continued 0 In connectronless cornrnunrcatron a datagrarn socket can be used to send to or receive from any other datagrarn socket in connectionoriented communication a datagrarn socket can only be used to send to or receive from the datagrarn socket attached to the other end of the connection Data for a datagrarn are placed in a byte array if a byte array of insuf cientlength is provided by a receiver the data received will be truncated The receive operationis blocking the send operation is nonblocking 0 02262000 CECS327 Netcenh1cCompuhng ServerSocket class It then accepts connection requests from other processes O 39 Aprocess a connectionrequestor creates a K data socket using the Socket class the l 39 constructor of whichissues a connection 0 request to the connectionacceptor O 0 02262000 CECS 327 Netcentric Computing Summary 6 Key points of secure sockets 0 Secure socket APls are available for transmission of con dential data 0 Well known secure socket APls include the 1 Secure Socket Layer SSL and Java s Secure Socket Extension JSSE Secure socket APls have methods that are similar to the connectionoriented socket APls O 0 02262000 CECS 327 Netcentric Computing Previously O RMI Stub downloading O DjavarmiservercodebaseltURLgt O RMI security manager 0 Java policy file 0 Djavasecuritypolicyltfull directory path to the policy fiegt Internet Applications Instructor Dr Jeho Park The World Wide Web 0 The web WWW is a distributed system of HTTP servers and clients more commonly known as web servers and web browsers 0 It is a clientserver application based on a protocol named the HyperText Transfer Protocol HTTP 0 It combines three important and wellestablished computing technologies 0 Hypertext documents 0 Networkbased information retrieval 0 Standard Generalized Markup Languages SGML The Hypertext Markup Language HTML 0 HTML is a markup language used to create documents that can be retrieved using the World Web Web HTML is based on SGML HTML markup can represent hypertext news mail documentation and hypermedia menus of options database query results simple structured documents with inlined graphics and hypertext views of existing bodies of information The Extensible Markup Language XML 0 Whereas HTML is a language that allows a document to be marked up for the presentation or display of the information contained in a document XML allows a document to be marked up for structured information 0 Also based on SGML XML uses tags to describe the information contained in a document ltmessagegt lttogtyouyourAddresscomlttogt ltfromgtmemyAddresscomltfromgt ltsubjectgtThts is a messageltsubjectgt lttextgt Hello world lttextgt ltmessagegt The HyperText Transfer Protocol HTTP 1 0 The first version of HTTP HTTP09 was a simple protocol for raw data transfer 0 The most widely used HTI39P version is H39ITP 10 which has a draft proposed by Tim Berners Lee 1991 but has no formal specification although its common usagequot is described in RFC1945 Since then an improved protocol known as HTTP11 has been developed and often adopted 0 The basics of the protocol is well represented in HTTP10 6 The HyperText Transfer Protocol HTTP 2 0 HTTP is a connectionoriented stateless requestresponse protocol An HTTP server or web server runs on TCP port 80 by default HTTP clients namely web browsers are processes which implements HTI39P to interacts with a web server to retrieve documents phrased in HTML whose contents are displayed according to the documents markups The HyperText Transfer Protocol HTTP 3 O In HTTP10 each connection allows only one round of requestresponse O A client obtains a connection issues a request 0 The server processes the request issues a response and closes the connection thereafter The HyperText Transfer Protocol HTTP 4 web server web browser request is a message in 3 parts ltc ommandgt ltdocument adddressgt ltHTTP versiongt an optional header optional data for CGI data using post method response response is a message consisting of 3 parts a status line of the format ltprotocolgtltstatus codegtltdescription header information which may span several lines the document itself Event Diagram describing an HTTP10 session 9 The HyperText Transfer Protocol HTTP 5 H39ITP is textbased the request and responses are character strings Each request and response is composed of these parts in order 0 The requestresponse line A header section A blank line The body A sample H39ITP session A sample HTTP session bash 3Z telnet wwwcecscsu1bedu 80 Trying 13413924982 Connected to prometheuscecscsu1bedu Escape character is 39AJ39 GET jpark HTTP10 HTTP Request HTTP11 2 0K HTTP response status line Date Mon 04 May 2009 064044 GMT HTTP response header Server Apache1323 Unix Red HatLinux PHP4ZZ modper11Z6 Connection close Content Type texthtml lthtm1gt Document content ltheadgt lttit1egtWe1come to Jeho Parklttit1egt ltmeta http equivquotContent Typequot contentquottexthtm1 charsetiso 8859 1quotgt ltstyle typequottextcssquotgt lt import ur1quotmysty1ecssquot gt ltsty1egt ltheadgt The HTTP request 0 A client request is sent to the server after the client has established a connection to the server 0 A request line is of the following form ltH7739P methodgtltspacegtltRequestURIgtltspacegtltprotocoI specificationgtrn where ltHTTP methodgt is the name of a method defined for the protocol ltRequest URIgt is the URI of a web document or more generally a web object ltprotoco specificationgt is a specification of the protocol observed by the client and ltspacegt is a space character 0 An example client request is as follows GET tndexhtm1 HTTP10 HTTP Methods in a client request lgt o The HTTP method in a client request is a reserved word in uppercase which specifies an operation of the server that the client desires 0 Some of the key client request methods are listed below GET for retrieving the contents of web object referenced by the specified URI HEAD for retrieving a header from the server only not the object itself POST used to send data to a process on the server host PUT used to request the server to store the contents enclosed with the request to the server machine in the file location specified by the URI l4 The Request Header 0 The request header fields allow the client to pass additional information about the request and about the client itself to the server These fields act as request modifiers with semantics equivalent to the parameters on a programming language method procedure invocation A header is composed of one or more lines each line in the form of ltkeywordgtltspacegtltvaluegtrn The Request Header Some of the keywords and values that may appear in a request header are 0 Accept content types acceptable by the client 0 UserAgent specifies the type of browser 0 Connection KeepAlive can be specified so that the server does not immediately close a connection after sending a response 0 Host host name of the server An example request header is as follows Accept Connection Keep Alive Host wwwsomehostedu User Agent Generic gtgt wtktpedta Request Body O A request optionally ends with a request body which contains data that needs to be transferred to the server in association with the request 0 For example if the POST method is specified in the request line then the body contains data to be passed to the target process Examples of a complete Client request Example1 GET HTTP11 ltblank linegt Example2 HEAD HTTP11 Accept Connection Keep Alive Host somehostcom User Agent Generic ltblank linegt Examples of a complete Client request Example3 POST serv1etmyServerservlet HTTP10 Accept Request Connection Keep Alive header Host somehostcom User Agent Generic ltblank linegt Namedonaldampemai1donaldsomeU edu Request body The H39ITP Server Response 0 In response to a request received from a client the H39ITP server sends to it a response 0 Like the request an HTI39P response is composed of these parts in order The response status line A header section A blank line The body The response status line The status line is in the form of ltprotocolgtltspgtltstatuscodegtltspgtltdescriptiongtrn The status code designations are as follows 100 199 200 299 300 399 400 499 500 599 Example 1 Informational Client request successful Client request redirected Client request incomplete Server errors HTTP10 200 OK Example 2 HTTP11 404 NOT FOUND A sample HTTP session revisited bash 3Z telnet wwwcecscsu1bedu 80 Trying 13413924982 Connected to prometheuscecscsu1bedu Escape character is 39AJ39 GET jpar39k HTTP10 HTTP Request HTTP11 2 0K 1 HTTP response status line Date Mon 04 May 2009 064044 GMT HTTP response header Server Apache1323 Unix Red HatLinux PHP4ZZ modper11Z6 Connection close Content Type texthtml lthtm1gt Document content ltheadgt lttit1egtWe1come to Jeho Parklttit1egt ltmeta http equivquotContent Typequot contentquottexthtm1 charsetiso 8859 1quotgt ltstyle typequottextcssquotgt lt import ur1quotmysty1ecssquot gt ltsty1egt ltheadgt HTTP Response Header The status line is followed by a response header A response header is composed of one or more lines each line in the form of ltkeywordgtltspacegtltvauegtrn There are two types of response header lines 0 Response header lines 0 Entity header lines HTTP Response Header Response header lines these header lines return information about the response the server and further access to the resource requested as follows Age seconds Location URI Retry After datelseconds Server string WWW Authenticate scheme realm HTTP Response Header Entity header lines these header lines contain information about the contents of the object requested by the client as follows Content Encoding Content Length Content Type typesubtype see MIME Expires date Last Modified date HTTP Response Header An Example response header is as follows Date Mon 30 Oct 2000 185208 GMT Server Apache139 Unix ApacheJServ10 Last modified Mon 17 June 2001 164513 GMT Content Length 1255 Connection close Content Type texthtml CECSSZ7 Spring 2009 The Client Server Paradigm 3 Instructor Dr Jeho Park Software Architecture of Distributed Applications Multilayer architecture prOVideS UI Presentation I provrdes Application Business Logic Corgeliaaglon a Hca on provides Service Data Access IOIO underlying senices for the top two layers W DB File Advantages of separating the layers of logic The separation allows each module to be developed by people with special skills to focus on a module for which they have expertise The separation allows modifications at one layer to be transparent to the other layers Software Engineering for a Network Service clientside software serverside software presentatlon loglc application logic apphcatlon 10glc service logic serv1ce logic Daytime Client server using Connectionless Datagram Socket Clientside Presentation Layer 0 DaytimeClient1java encapsulates the clientside presentation logic that is it provides the interface for a user of the client process 0 Note that the code in this class is concerned with obtaining input the server address from the user and displaying the output the timestamp to the user To obtain the timestamp a method call getTimeStamp to a helper class DaytimeClientHelper1java is issued 39 This method getTimeStamphostname portnumber hides the details of the application logic and the underlying service logic In particular the programmer of DaytimeClient1java need not be aware of which socket type is used for the IPC Daytime Client server using Connectionless Datagram Socket continued Clientside Application Logic Layer 0 The DaytimeCientHeper1java class Figure 6b encapsulates the clientside application logic This module performs the IPC for sending a request and receiving a response using a specialized class of the DatagramSocket MyCientDatagramSocket Note that the details of using datagram sockets are hidden from this module In particular this module does not need to deal with the byte array for carrying the payload data Clientside Service Layer The MyCientDatagramSocketjava class provides the details of the IPC service in this case using the datagram socket API Serverside software Presentation Layer Typically there is very little presentation logic on the serverside In this case the only user input is for the server port which for simplicity is handled using a commandline argument Application Logic Layer The DaytimeServer1java class encapsulates the serverside application logic This module executes in a forever loop waiting for a request form a client and then conduct a service session for that client The module performs the IPC for receiving a request and sending a response using a specialized class of the DatagramSocket MyServerDatagramSocket Note that the details of using datagram sockets are hidden from this module In particular this module does not need to deal with the byte array for carrying the payload data Server side software cont Service Layer The MyServerDatagramSocketjava class provides the details of the IPC service in this case using the datagram socket API Example protocol daytime Defined in RFC867 sequence diagram data representation text character strings data format In contains a timestamp in a format such as Wed Jan 30 095248 2002 Daytime service data representation in RFC 867 Daytime Syntax There is no speci c syntax for the daytime It is recommended that it be limited to the ASCII printing characters space carriage return and line feed The daytime should be just one line One popular syntax is Weekday Month Day Year Time Zone Example Tuesday February 22 1982 173743 PST Daytime Protocol sequence diagram data representation text character strings data format m1 a null message contents will be ignored m2 contains a timestamp in a format such as Wed Jan 30 095248 2002 Daytime Protocol Implementation Sample 1 using connectionless sockets DaytimeServer1 java DaytimeClient1java The getAddress and getPort Methods of DatagramPaCket Class Method of DatagramPacket class Description public InetAddress getAddress Return the IP address of the remote host from a socket of which the datagram was received public int getPort Return the port number on the remote host from a socket of which the datagram was received UDP Header 0 16 16rhit destination port number 16rhit source port number 16rbit UDP checksum l6rhit UDP length data if any IP Header 0 4bit 4b1t header 8bit type of serv1ce 164m tot a1 length in bytes version length 13bit fragment offset 16bit identi cation 0 DM FF 8bit time to live TTL 8bit protocol 16bit header checksurn 32bit source IP address 32bit destinatioan address options if any UML Class Diagram a subset frequently used in the book Class A Class A Interface A Attributes Attributes Operations Operations Operations i Class B Class B Class B Attributes Attributes Attributes Operations Operations Operations Class B depends Class B inherits Class B implements on Class A from Class A Interface A UML Diagram for the datagram DaytimeCient7 presentation layer DnytimeClientl Datagraml acet MyC lientDatagram quot SDCket DatagramSocket DaytimeClientHelperl sendMessageO receiveMessageO application logic layer service layer UML Diagram for the datagram DaytimeServer7 DatagramPacet DatagramMessage presentation application logic layer DaytimeServerl E MyServe rDatagram Socket 7 DatagramSocket sendMessage receiveMessage receiveMessageAnd Sender service layer
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'