ITEC 4020A:Internet Client Server Systems Professor: Marin Litoiu Lectures 3&4: Internet Protocols © Marin Litoiu, York University, Canada This lecture uses captions from “Distributed Systems: Concepts and Design, 4/E, by Dean Dollimore, Tim Kindberg, George Coulouris
Content Networks HTTP protocols Servlets JSP Model View Controller Summary © Marin Litoiu, York University, Canada
Networks Networks: transmission media ( wire, cable, fibre, wireless), hardware devices( interfaces, routers) and software ( drivers, protocols) Latency: the time from when the data leaves the computer till it reaches the destination In most media, the bits go with the sped of light On the fastest link between Europe and Australia, the latency is 0.13s Latency=distance/(speed of the data) Data transfer rate(bandwidth): bits send/received per second Message transmission time=latency+length/(data transfer rate) Q: how long takes to transfer 2MB data between two computers located at 7000Km of each other? Assume a transmission rate of 20KB/s and that data travels with the speed of light A:T=(7000/300000)+ 2000/20= seconds © Marin Litoiu, York University, Canada Applications, services (Your project, for example) Computer and network hardware Platform Operating system (Windows, Linux, Mac OS) Middleware (RPC, CORBA, RMI, DCOM, Web Services) Network software(TCP/IP) Applications
Networks and their performance: bandwidth and latency ExampleRangeBandwidth (Mbps) Latency (ms) Wired: LANEthernet1-2 kms WANIP routingworldwide MANATM250 kms InternetworkInternetworldwide Wireless: WPANBluetooth ( ) m WLAN WiFi (IEEE ) km WMAN WiMAX (802.16)550 km WWAN GSM, 3G phone netsworldwide © Marin Litoiu, York University, Canada
Routing in a wide area network affects latency and bandwidth Hosts Links or local networks A DE B C Routers connection message © Marin Litoiu, York University, Canada
Protocol layers in the ISO Open Systems Interconnection (OSI) model © Marin Litoiu, York University, Canada
OSI protocol summary LayerDescriptionExamples ApplicationProtocols that are designed to meet the communication requirements of specific applications, often defining the interface to a service. HTTP, FTP,SMTP, CORBA IIOP PresentationProtocols at this level transmit data in a network representation that is independent of the representations used in individual computers, which may differ. Encryption is also performed in this layer, if required. Secure Sockets (SSL), SessionAt this level reliability and adaptation are performed, such as detection of failures and automatic recovery. TransportThis is the lowest level at which messages (rather than packets) are handled. Messages are addressed to communication ports attached to processes, Protocols in this layer may be connection-oriented or connectionless. TCP,UDP NetworkTransfers data packets between computers in a specific network. In a WAN or an internetwork this involves the generation of a route passing through routers. In a single LAN no routing is required. IP,ATM virtual circuits Data linkResponsible for transmission of packets between nodes that are directly connected by a physical link. In a WAN transmission is between pairs of routers or between routers and hosts. In a LAN it is between any pair of hosts. Ethernet MAC, ATM cell transfer, PPP PhysicalThe circuits and hardware that drive the network. It transmits sequences of binary data by analogue signalling, using amplitude or frequency modulation of electrical signals (on cable circuits), light signals (on fibre optic circuits) or other electromagnetic signals (on radio and microwave circuits). Ethernet base- band signalling,ISDN © Marin Litoiu, York University, Canada
TCP/IP layers Application protocols: ftp, http, smtp A message is split in “packets” Each packet is transmitted independently TCP: transport control protocol A “channel is established between source and destination The source checks that each packet is delivered to destination Eventually retransmits the packets The protocol is reliable, it guarantees transmission UDP: user datagram protocol Each packet might have its own route The sender does not check if each packet arrived at destination The protocol is not reliable IP: internet protocol Adds the IP addresses ( of the source and destination) to the packet Routes the packets to the first router Messages (UDP) or Streams (TCP) Application Transport Internet UDP or TCP packets IP datagrams Network-specific frames Message Layers Underlying network Network interface © Marin Litoiu, York University, Canada
IP packet layout © Marin Litoiu, York University, Canada
Client Server programming HTTP Servlets and JSP © Marin Litoiu, York University, Canada network ClientServer Client libraryServer library
HTTP (Hyper Text Transfer Protocol) Client sends a message(request); the server responds with another message( reply) The message includes the method name, the arguments, the results of the method and how data is represented http 1.0 was connectionless The server closes its connection, release its resources after first request http 1.1 connection oriented The server keeps the connection open; subsequent requests from the same client are served faster The server listen ( usually) on port 80 The messages are delivered through the underlying TCP/IP protocol © Marin Litoiu, York University, Canada Request HTTP Server(Web Server) HTTP Client(Browser) (wait) Reply message Get the message Select the method -GET -PUT -POST... Execute the method Return a result message TCP IP Socket Port 80 Socket Any port
HTTP request and reply messages Methods GET: requests a resource whose URL (locator) follows HEAD: Identical to GET, does not return data, but info about the data( size, type, etc..) POST: specify the URL of a resource that can process the data ( used for forms, when you send user data to the server PUT: store the data to the URL specified DELETE: deletes the resource specified TRACE: the server sends back the request message; used for diagnostic OPTIONS: the server sends back the methods it supports and its special requirements © Marin Litoiu, York University, Canada GET// 1.1 URL or pathnamemethodHTTP versionheadersmessage body HTTP/1.1200OK resource data HTTP versionstatus codereasonheadersmessage body
Writing a Java HTTP Client import java.net.*; import java.io.*; public class HTTPClient { public static void main(String[] args) throws Exception { URL york = new URL(" URLConnection yc = york.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } © Marin Litoiu, York University, Canada HTTP classes are in the java.net package To connect to a server, you open an URL connection Then you read from that connection
Your turn What is HTTP programming Name 4 server Http methods What do you need to know about the server in order to write a http client? In http programming, how would one write a server program? © Marin Litoiu, York University, Canada
Servlet Handle HTTP GET and POST methods on server side A servlet is a Java class with two main methods: doGet and doPost Functionality Handle requests coming from clients Possibly generate responses for the clients Other methods init -- called before handling any request getServletInfo getServletConfig The servlet can be invoked manually (in a browser) or programmatically, from another program ( see next slides) A servlet runs in a web/application server ( Tomcat, Websphere…) © Marin Litoiu, York University, Canada
doGet and doPost --Method signatures public class SampleServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //add your implementation } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // add your implementation } Request- contains the information coming from client Response- contains the information going to the client © Marin Litoiu, York University, Canada
Servlet- An Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" "); out.println(" Hello 4020 World! "); out.println(" "); out.println(" Hello World! "); out.println(" "); out.println(" "); } What does this servlet do? How do you invoke this servlet? What is the URL of the servlet? © Marin Litoiu, York University, Canada
HttpServletRequest protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //add your implementation Input for both doGet and doPost Methods: String getParameter (String paramName) HttpSession getSession (boolean createFlag) Ex: request.getParameter(“language”) request.getSession(true) © Marin Litoiu, York University, Canada
HttpServletRespons protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //add your implementation Input for both doGet and doPost Methods: PrintWriter getWriter () void setContentType (String contentType) Ex:response.getWriter() response.setContentType(”html”) © Marin Litoiu, York University, Canada
Calling a servlet Explicit URL where servletName can be of form servletClass.class Implicit call – using a form’s action attribute Get parameters can be sent with the URL url?param1name=param1value¶m2name=param2value&… © Marin Litoiu, York University, Canada
Session tracking Need for session tracking HTTP has no session tracking features Distinguish between multiple clients “remember” information specific to clients Can be done with cookies Class HttpSession – Java class for session tracking Lifetime of an HttpSession object Lifetime of other objects (request, response) © Marin Litoiu, York University, Canada
Additional resources Read the “Basics” Chapter of your textbook Try the Servlets examples: You can view the source and execute the servlet It is time to test your server environment, see the link: It is recommended that you use a development environment: Eclipse: for code development Tomcat : for deployment and testing MySql: for database See the “Resources” on the course web site on how to install them on your computer © Marin Litoiu, York University, Canada
JSP Motivation Definition: JSP = HTML + Java © Marin Litoiu, York University, Canada
Overview Java components in JSPs: Directives: define page settings, compilation time includes, custom tag libraries specification Actions: functionality encapsulated in predefined tags (jsp:useBean, jsp:include = call time include) Scriptlets: Java code Tag libraries: custom tag extensions JSP usage:when an HTML page must be customized Life cycle: when a JSP is called it is first translated into a servlet © Marin Litoiu, York University, Canada
Implicit objects: Scopes Scopes Application: owned by the servlet container Page: objects exist only in the page where they are defined Request: exist in the interval between receiving the request by the container and sending the response (Remark: can have the request forwarded from resource_1 to resource_2) Session: exist during the duration of a session © Marin Litoiu, York University, Canada
JSP Sample: Hello World page language="java" contentType="text/html; charset=ISO " pageEncoding="ISO "%> Insert title here Hello 4020 © Marin Litoiu, York University, Canada
Model View Controller Architecture © Marin Litoiu, York University, Canada Data base Java Beans
A MVC Example If the user types “french”, he/she is greeted in French, otherwise in English © Marin Litoiu, York University, Canada Browser GreetingsJSP.jsp MultiLingualServlet.java hello.jsp Bonjour.jsp
JSP and forms (The View) Greetings Language The “form” above has a button, labelled “Say it” a text box named “language” When the button is pressed, a servlet named MultiLingualServlet is invoked (its method doPost) © Marin Litoiu, York University, Canada
Servlet (The Controller) protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //this parameter comes from the client and is inserted into the request ( see the GreetingsJSP.jsp page) String greetings=request.getParameter("language"); try { //based on the value of the parameter “language”, we invoke the Bonjour.jsp, or the Hello.jsp page... if (greetings.equals("french")) //this is how you forward the request to another object. Note that you pass the request and response getServletConfig(). getServletContext().getRequestDispatcher( "/Bonjour.jsp").forward(request, response); else getServletConfig().getServletContext().getRequestDispatcher("/Hello.jsp").forward(request, response); } catch(Exception e) { e.printStackTrace(); } © Marin Litoiu, York University, Canada
Another View ( Bonjour.jsp) page language="java" contentType="text/html; charset=ISO " pageEncoding="ISO "%> Bonjour Bonjour 4020 © Marin Litoiu, York University, Canada
Another example: MVC with JSP, Servlets, Beans © Marin Litoiu, York University, Canada Register names, retrieve names 1. shows a form; user inputs first, last names; 2. a servlet is invoked when “submit” is pressed; 3. the servlet retrieves or creates a Bean, Name, fills in the fields, and then save ssthe bean in the “session” object; 4. the servlet passes the control to ShowNames.jsp; 5. ShowNames retrieves the bean fields and display she names. Browser UserReg.jsp UserRegistration.java Name.java ShowNames. jsp
UserReg.jsp: filling the forms… Greetings First Name Last Name When done (button “Submit” pressed) invoke the servlet “UserRegistration” Notice the names of the fields, you need to remember those when implement the servlet UserRegistration.. © Marin Litoiu, York University, Canada
The bean Name: stores the data package users; public class Name { private String firstName="first name missing"; private String lastName="last name missing"; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } A bean is a java object To set and get the field X of a bean, you use setX, getX methods… Do not initialize the fields to constructors © Marin Litoiu, York University, Canada
The UserRegistration servlet ( controller) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get the session object, by calling a request method HttpSession session= request.getSession(); //once I have the session, I want to know if the session has an object Name --- named "NameBean"--- Name nameBean= (Name)session.getAttribute("NameBean"); if (nameBean==null) { // if it does not, I need to create an object Name nameBean=new Name(); } //now get the attributes that came from client ( see the UserReg.jsp for the form and its text fields... ) String fn= request.getParameter("firstName"); if ((fn!=null)&&(!fn.trim().equals(""))){ nameBean.setFirstName(fn); } //get the last name... String ln= request.getParameter("lastName"); if ((ln!=null)&&(!ln.trim().equals(""))){ nameBean.setLastName(ln); } © Marin Litoiu, York University, Canada
….The UserRegistration servlet ( controller) ……. //store the bean in the session and request objects so other servlets or JSP can use them ( see ShowNames.jsp) session.setAttribute("NameBean", nameBean); request.setAttribute("NameBean", nameBean); //pass the control to a JSP... getServletConfig(). getServletContext().getRequestDispatcher( "/ShowNames.jsp").forward(request, response); } © Marin Litoiu, York University, Canada
And finally….ShowNames.jsp Retrieves the bean “nameBean” from the session object Displays the field “firstName” of the bean Displays the fields “lastName” of the bean © Marin Litoiu, York University, Canada
Summary Networks Network protocols are organized in layers TCP, UDP IP Programming at the network layers are done through sockets HTTP GET POST Servlets: user requests are forwarded to doGet and doPost Java Server Pages HTML+java Are compiled to Servlets Model View Controller JSP- View Servlet –Controller Java beans( interacting with the database) - Model © Marin Litoiu, York University, Canada