Académique Documents
Professionnel Documents
Culture Documents
Networking
Socket Programming
connecting processes
6/2/2012
Introduction to Sockets
Introduction to Sockets
Why Sockets? Used for Interprocess communication. The Client-Server model Most interprocess communication uses client-server model Client & Server are two processes that wants to communicate with each other The Client process connects to the Server process, to make a request for information/services own by the Server. Once the connection is established between Client process and Server process, they can start sending / receiving information. What are Sockets? End-point of interprocess communication. An interface through which processes can send / receive information
Socket
6/2/2012
Introduction to Sockets
What exactly creates a Socket? <IP address, Port #> tuple What makes a connection? {Source<IP address, Port #> , Destination <IP address, Port #>} i.e. source socket destination socket pair uniquely identifies a connection. Example
1343
Client
192.168.0.2 1343
Server
192.168.0.1
80
Client
192.168.0.3
5488
Client
192.168.0.2
Introduction to Sockets
Socket Types STREAM uses TCP which is reliable, stream oriented protocol DATAGRAM uses UDP which is unreliable, message oriented protocol RAW provides RAW data transfer directly over IP protocol (no transport layer) Sockets can use unicast ( for a particular IP address destination) multicast ( a set of destinations 224.x.x.x) broadcast (direct and limited) Loopback address i.e. 127.x.x.x
6/2/2012
6/2/2012
6/2/2012
When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.
Socket clientSocket = null; try { clientSocket = MyService.accept(); } catch (IOException e) { System.out.println(e); }
The class DataInputStream allows you to read lines of text and Java primitive data types in a portable way. It has methods such as read, readChar, readInt, readDouble, and readLine,. On the server side, you can use DataInputStream to receive input from the client:
DataInputStream input; try { input = new DataInputStream(clientSocket.getInputStream()); } catch (IOException e) { System.out.println(e); }
6/2/2012
The class PrintStream has methods for displaying textual representation of Java primitive data types. Its write and println methods are important. Also, you may want to use the DataOutputStream:
DataOutputStream output; try { output = new DataOutputStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); }
Many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.
6/2/2012
HTTP
6/2/2012
URI,URN,URL
Uniform Resource Identifier
Information about a resource
6/2/2012
HTTP - URLs
URL
Uniform Resource Locator
protocol (http, ftp, news) host name (name.domain name) port (usually 80 but many on 8080) directory path to the resource resource name
http://xxx.myplace.com/www/index.html http://xxx.myplace.com:80/cgi-bin/t.exe
HTTP - methods
Methods
GET
retrieve a URL from the server
simple page request run a CGI program run a CGI with arguments attached to the URL
POST
preferred method for forms processing run a CGI program parameterized data in sysin more secure and private
10
6/2/2012
HTTP - methods
Methods (cont.)
PUT
Used to transfer a file from the client to the server
HEAD
requests URLs status header only used for conditional URL handling for performance enhancement schemes
retrieve URL only if not in local cache or date is more recent than cached copy
and a URL
11
6/2/2012
12
6/2/2012
From:
In internet mail format, the requesting user Does not have to correspond to requesting host name (might be a proxy) should be a valid e-mail address
Accept-Encoding
Like Accept but list is a list of acceptable encoding schemes Ex
Accept-Encoding: x-compress;x-zip
13
6/2/2012
User-Agent
Software product used by original client <field> = User-Agent: <product> <product> = <word> [/<version>] <version> = <word> Ex.
User-Agent: IBM WebExplorer DLL /v960311
Referer
For Servers benefit, client lists URL od document (or document type) from which the URL in request was obtained. Allows server to generate back-links, logging, tracing of bad links Ex.
Referer: http:/www.w3.com/xxx.html
14
6/2/2012
Authorization:
For Password and authentication schemes Ex.
Authorization: user fred:mypassword Authorization: kerberos kerberosparameters
ChargeTo:
Accounting information Accounting system dependent
15
6/2/2012
Pragma:
Same format as accept for servers should be passed through proxies, but used by proxy only pragma currently defined is no-cache; proxy should get document from owning server rather than cache
Modified-Since:
Used with GET to make a conditional GET if requested document has not been modified since specified date a Modified 304 header is sent back to client instead of document
client can then display cached version
16
6/2/2012
Response Packets
Sent by server to client browser in response to a Request Packet
Status Header
HTTP/1.0 sp code Codes:
1xx - reserved for future use 2xx - successful, understood and accepted 3xx - further action needed to complete 4xx - bad syntax in client request 5xx - server cant fulfill good request
17
6/2/2012
Status Codes
200 OK 201 created 202 accepted 204 no content 301 moved perm. 302 moved temp 304 not modified 400 bad request 401 unauthorized 403 forbidden 404 not found 500 int. server error 501 not impl. 502 bad gateway 503 svc not avail
18
6/2/2012
Statelessness
Because of the Connect, Request, Response, Disconnect nature of HTTP it is said to be a stateless protocol
i.e. from one web page to the next there is nothing in the protocol that allows a web program to maintain program state (like a desktop program). state can be maintained by witchery or trickery if it is needed
19
6/2/2012
Servlets
Easy to manage - client side management is NOT required Data consistency is easy and simple to achieve, as all components at one place As application size grows, difficult to maintain and reuse
20
6/2/2012
Database Server
1. 2.
Order fulfillment Application accessing Customer Information Customer care operations accessing same Customer DB
Business logic can change more easily Complexity introduced in the middle tier
21
6/2/2012
Database Server Thin Clients Presentation Logic Business Logic Data Access Layer
More loosely coupled More reusable Zero client management Complexity in the middle tier
22
6/2/2012
Client Tier
Middle Tier
browser
File system
Introduction
Servlets are modules that extend request/responseoriented servers, such as Java-enabled web servers. Servlets are to servers what applets are to browsers: an external program invoked at runtime. Unlike applets, however, servlets have no graphical user interface. Servlets can be embedded in many different servers because the servlet API, which you use to write servlets, assumes nothing about the server's environment or protocol. Servlets are portable.
23
6/2/2012
Servlet Basics
It runs inside a Java Virtual Machine on a server host. Unlike applets, servlets do not require special support in the web browser. The Servlet class is not part of the Java Development Kit (JDK). You must download the JDSK (Java Servlet Development Kit). A servlet is an object. It is loaded and runs in an object called a servlet engine, or a servlet container.
24
6/2/2012
A generic servlet should override the service( ) method to process requests and generate appropriate responses. An HTTP servlet overrides the doPost( ) and/or doGet( ) method.
Servlet Interface
methods to manage servlet
GenericServlet
Interface Clas s implements
GenericServlet
implements Servlet
HttpServlet
HttpServlet
extends GenericServlet exposes HTTP-specific functionality
Clas s
UserServlet
extends Class Class Override one or more of: doGet() doPost() service() ...
25
6/2/2012
service ( )
A simple Servlet
public class SimpleServlet extends HttpServlet { /** * Handle the HTTP GET method by building a simple web page. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println("<HTML><HEAD><TITLE>"); out.println(title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); out.println("</BODY></HTML>"); out.close(); } }
26
6/2/2012
Do not worry about synchronization Perform costly setup here, rather than for each request
open database connection load in persistent data spawn background threads
init()
init() should be completed before starting to handle requests If init() fails, UnavailableException is thrown Invocation process allows to look-up for the initialization parameters from a configuration file
getInitParameter(paramName) method is used to read the parameters
init() parameters are set by the administrator servlet parameters are set by the invocation
27
6/2/2012
After the service loads and initializes the servlet, the servlet is able to handle client requests public void service(ServletRequest req, ServletResponse res)
takes Request and Response objects called many times, once per request
28
6/2/2012
Servlets run until they are removed When a servlet is removed, it runs the destroy() method The destroy() method is run only once
the servlet will not run again unless it is reinitialized
Releasing the resources is the developers responsibility close database connections stop threads Other threads might be running service requests, so be sure to synchronize, and/or wait for them to quit Destroy can not throw an exception
use server-side logging with meaningful message to identify the problem
29
6/2/2012
Servlet Lifecycle
30
6/2/2012
Requests and Responses Methods in the HttpServlet class that handle client requests take two arguments:
An HttpServletRequest object, which encapsulates the data from the client An HttpServletResponse object, which encapsulates the response to the client
public void doGet (HttpServletRequest request, HttpServletResponse response) public void doPost(HttpServletRequest request, HttpServletResponse response)
HttpServletRequest Objects
as any cookies found in the request and the HTTP method with which the request was made. The HttpServletRequest object also allows you to obtain the arguments that the client sent as part of the request. To access client data:
The getParameter() method returns the value of a named parameter. If your parameter could have more than one value, use getParameterValues() instead. The getParameterValues() method returns an array of values for the named parameter. (The method getParameterNames() provides the names of the parameters.) For HTTP GET requests, the getQueryString method returns a String of raw data from the client. You must parse this data yourself to obtain the parameters and values.
31
6/2/2012
HttpServletRequest Interface
public String ServletRequest.getQueryString( ); returns the query string of the requst. public String getParameter(String name): given the name of a parameter in the query string of the request, this method returns the value. String id = getParameter(id) public String[ ] GetParameterValues(String name): returns multiple values for the named parameter use for parameters which may have multiple values, such as from checkboxes. String[ ] colors = req.getParmeterValues(color); if (colors != null) for (int I = 0; I < colors.length; I++ ) out.println(colors[I]); public Enumeration getParameterNames( ): returns an enumeration object with a list of all of the parameter names in the query string of the request.
HttpServletResponse Objects
An HttpServletResponse object provides two ways of returning data to the user:
The getWriter method returns a Writer The getOutputStream method returns a ServletOutputStream
Use the getWriter method to return text data to the user, and the getOutputStream method for binary data. Closing the Writer or ServletOutputStream after you send the response allows the server to know when the response is complete.
32
6/2/2012
HttpServletResponse Interface
public interface HttpServletResponse extends ServletResponse: The servlet engine provides an object that implements this interface and passes it into th servlet through the service method Java Server Programming public void setContentType(String type) : this method must be called to generate the first line of the HTTP response:
setContentType(text/html);
public PrintWriter getWriter( ) throws IOException: returns an object which can be used for writing the responses, one line at a time:
PrintWriter out = res.getWriter; out.println(<h1>Hello world</h1>);
33
6/2/2012
34
6/2/2012
35
6/2/2012
Cookies in Java
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets. The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servelet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies( ) method. Several cookies might have the same name but different path attributes.
36
6/2/2012
37
6/2/2012
38
6/2/2012
Session object allows session state information to be maintained without depending on the use of cookies (which can be disabled by a browser user.) Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.
A Session object
servelet engine
servlet
39
6/2/2012
40
6/2/2012
41
6/2/2012
Allows servlets that are executing on the same Web server to:
Communicate with each other Share resources amongst each other
The RequestDispatcher interface can be used to invoke a servlet from the other
42
6/2/2012
The following are few methods that can be used for communication between servlets
Method name getServletContext() Description This method belongs to the interface javax.servlet.ServletConfig public abstract ServletContext getServletContext() This function returns the context of the servlet. getRequestDispatcher() public abstract RequestDispatcher getRequestDispatcher(String urlpath) This method is used to get a reference to a servlet through an URL that is specified as the parameter. The dispatcher that is returned is used to invoke the servlet. If a dispatcher cannot be obtained for the URL specified, this function returns a null.
Description public abstract void forward(ServletRequest request,ServletResponse response) throws ServletException, IOException This method belongs to the RequestDispatcher interface and can be used to forward a request from one servlet to another. This method must be used when the output is completely generated by the second servlet or the servlet that is invoked.
include()
public abstract void include(ServletRequest request,ServletResponse response) throws ServletException, IOException This function is also used to invoke one servlet from another like the forward() function. However, you can also include the output of the first servlet with the current output.
43
6/2/2012
forward
The forward method of the RequestDispatcher interface may only be called by the calling servlet if no output has been committed to the client. If output exists in the response buffer that has not been committed, it must be reset (clearing the buffer) before the target servlets service method is called. If the response has been committed, an IllegalStateException must be thrown.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOExcep tion, ServletException { ServletContext context = getServletContext(); RequestDispatcher dispatcher = context.getRequestDispatcher("/myServlet"); dispatcher.forward(req,res); } }
44
6/2/2012
include
The include method of the RequestDispatcher interface may be called at any time. The target servlet has access to all aspects of the request object, but can only write information to the response object as well as the ability to commit a response by either writing content past the end of the response buffer or explicitly calling the flush method of the ServletResponse interface. The included servlet cannot set headers or call any method that affects the headers of the response. Any attempt to do so should be ignored.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOExcep tion, ServletException { ServletContext context = getServletContext(); RequestDispatcher dispatcher = context.getRequestDispatcher("/myServlet"); dispatcher.forward(req,res); } }
45
6/2/2012
You need to deposit money into your account. Create a servlet that accepts the account number and pin number. The first servlet should also validate the account number and pass it on to the second servlet. The second servlet should accept the amount to be deposited from the user. The third servlet updates the table and displays the updated balance to the user. In addition, the third servlet also displays the last 20 transactions for that user. The fourth servlet should display the last 20 transactions for that user.
Task List Identify the mechanism Write the client interface Write the code for servlet 1 Write the code for servlet 2 Write the code for servlet 3 Write the code for servlet 4 Compile the servlets Deploy the servlets in J2EE Verify the servlets
46
6/2/2012
47
6/2/2012
Task 3: Write code for servlet 1 The first servlet uses the login table to validate the account number and the pin number If the values are valid, an attribute called accountnumber is created and assigned the value entered Else, an error message is displayed to the user The attribute is created by using the setAttribute() method
48
6/2/2012
49
6/2/2012
Summary
In this lesson, you learned that: RequestDispatcher interface can be used to call one servlet from the other The forward() and the include() method can be used to invoke one servlet from the other
The data, which is common to servlets can be accessed by using the ServletContext interface.
50
6/2/2012
51
6/2/2012
JSP
52
6/2/2012
53
6/2/2012
Disadvantages of Servlets
Need to be Java programmer Presentation buried in code Cant use web page design tools
JSP is a server-side scripting language that produces Web pages that can be viewed with any browser You can mix regular HTML tags with JSP script in the same JSP page The JSP scripts, if any, are interpreted on the Web server (often called the application server) The content generated by the execution of JSP code is mixed with HTML code and the whole content is sent to the client browser Client never sees JSP part!
54
6/2/2012
JSP file The current date and time on the Web server are: <%= new java.util.Date() %>
Content sent to client The current date and time on the Web server are: Mon Jul 16 10:58:09 PDT 2007
JSP script executes on the Web server and the current date and time are generated
55
6/2/2012
Access file systems via the Internet so that you can read, write, and update files.
Utilize extensive Java Application Programming Interfaces.
56
6/2/2012
57
6/2/2012
58
6/2/2012
Actions
dynamically generate content upon client request some built in actions can create our own xml syntax
59
6/2/2012
No space between % and = Expression is converted to a String and embedded directly in page
<%! %> declares things that are inserted directly into implementation class in servlet
60
6/2/2012
61
6/2/2012
<HTML> <HEAD> <TITLE>JSP output example 2</TITLE> </HEAD> <BODY> Your message is displayed using your preferred font format as follows:<br><br> <% out.println("<hr size=2 color=red>"); out.print("<font size= "); out.print(request.getParameter("fontSize")); out.print(" color= "); out.print(request.getParameter("fontColor")); out.println(">"); out.println(request.getParameter("message")); out.println("</font>" ); out.println("<hr size=2 color=red>"); %> </BODY> </HTML>
62
6/2/2012
<% // Retrieve form info and store in String // variable String major = request.getParameter(major); // // later display using out object out.println("Your major is " + major); %> <!- alternatively use expression --> Your major is <%= major %>
63
6/2/2012
Page Directives
Page directive attributes apply to the entire JSP page: <%@ page attribute1=value1 attribute3= %> OR <%@ page attribute1=value1 %> <%@ page attribute2=value2 %> attribute2=value2
64
6/2/2012
Import Attribute
Make Java classes available to the scripting environment Use Java API to add power to your JSP script Reference class without specifying package names
<%@ page import=java.util.*,java.sql.* %>
65
6/2/2012
Session Attribute
HTTP is stateless
JSP provides session management
Session Attribute
A session begins when a user requests a JSP page the first time Session can be destroyed many different ways
User closes web browser Server terminates due to inactivity You can terminate session in code
66
6/2/2012
67
6/2/2012
Buffer Attribute
Specifies the size of the buffer used by the implicit out variable
<%@ page buffer=sizekb %> <%@ page buffer=none %>
If a buffer is specified then output is buffered with a buffer size not less than the specified size
68
6/2/2012
isThreadSafe Attribute
Specify whether to allow more than one thread to execute the JSP code
69
6/2/2012
Include Files
Add content from another file to your page Could be static content
Include Directive
Format
<%@ include file=relative URL %>
Alternative format (xml) <jsp:directive.include file=relative URL /> Included content is merged into page at translation time!
This is called a static include Can result in inconsistencies when included file is updated Updates are not reflected in already translated pages!
70
6/2/2012
Include Action
Form
<jsp:include page="Relative URL" flush="true" />
The action does not merge the actual contents of the specified page at translation time The page is included each time the JSP page is requested
Updates are always reflected
This is an action, not a directive Performance cost to do this flush set to true to force current page buffer to be flushed before new file is included
Variable Duration
The duration of variable (also called its lifetime) is the period during which the variable exists in memory Variables of instance duration exist throughout the lifetime that a servlet is loaded in memory Variables of local duration exist only during processing of single page
71
6/2/2012
72
6/2/2012
Implicit Objects
Implicit Objects
Objects created by the servlet container application session request response exception out Config pageContext page
73
6/2/2012
The JSP implicit application object is an instance of a java class that implements the javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and set information about the web application in which it is running.
74
6/2/2012
The JSP implicit session object is an instance of a java class that implements the javax.servlet.http.HttpSession interface. It represents a client specific conversation.
The session implicit object is used to store session state for a single user.
One.jsp <html> <body> <% session.setAttribute(variable1,value1); RequestDispatcher rd=request.getRequestDispatcher(two.jsp); rd.forward(request,response); %> </body> </html> two.jsp <html> <body> <% =session.getAttribute(variable1) %> </body> </html>
75
6/2/2012
The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.
76
6/2/2012
The JSP implicit request object is an instance of a java class that implements the javax.servlet.http.HttpServletRequest interface. It represents the request made by the client.
The request implicit object is generally used to get request parameters, request attributes, header information and query string values.
request implicit object Login.html <html> <body> <form method=get action=LoginValidation.jsp> UserName: <input type=text name=userName /> Password: <input type=password name=password/> <input type=submit value=login/> </form> </body> </html>
77
6/2/2012
78
6/2/2012
79
6/2/2012
The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occured exception that caused the control to pass to the JSP error page.
The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.
80
6/2/2012
81
6/2/2012
The JSP implicit pageContext object is an instance of the javax.servlet.jsp.PageContext abstract class. It provides useful context information. That is it provides methods to get and set attributes in different scopes and for transfering requests to other resources. Also it contains the reference to to implicit objects.
82
6/2/2012
Page Scope
page scope means, the JSP object can be accessed only from within the same page where it was created. The default scope for JSP objects created using <jsp:useBean> tag is page.
JSP implicit objects out, exception, response, pageContext, config and page have page scope.
Request Scope
A JSP object created using the request scope can be accessed from any pages that serves that request. More than one page can serve a single request. The JSP object will be bound to the request object. Implicit object request has the request scope.
83
6/2/2012
Session Scope
session scope means, the JSP object is accessible from pages that belong to the same session from where it was created. The JSP object that is created using the session scope is bound to the session object. Implicit object session has the session scope.
Application scope
A JSP object created using the application scope can be accessed from any pages across the application. The JSP object is bound to the application object. Implicit object application has the application scope.
84
6/2/2012
JSP Standard actions JSP Standard action are predefined tags which perform some action based on information that is required at the exact time the JSP page is requested by a browser.
for instance, access parameters sent with the request to do a database lookup The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
<jsp:forward>
<jsp:param>
<jsp:plugin>
85
6/2/2012
The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or a dynamic resource in a JSP file. The results of including static and dynamic resources are quite different. If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page. The syntax for the jsp:include element is:
86