Vous êtes sur la page 1sur 6

2/24/12 EchoExample - jquery-stream - Echo Example - Comet Streaming JavaScript Library - Google Project

1/6 code.google.com/p/jquery-stream/wiki/EchoExample
Project Home Downloads Wiki Issues Source
Updated Aug 14, 2011 by fl owersi ...@gmai l .com
My favorites | Sign in
jquery-stream
Comet Streaming JavaScript Library
Search projects
Search Current pages for Search
EchoEample
Echo Eample
Pleae, ee ChaEample fo pacical e. Thi iki ill no be pdaed.
Echo Eample
Echo Example
Web Page
WebSocket /HTTP Echo Server
Java - Servlet 3.0
Java - Servlet 3.0 and Jetty 8
Web Page
Web Page is an echo client.
Whenever user enters a message, the page makes JavaScript object containing it and send it to the echo server using the jQuery Stream, and
when a message returns from the server, the page displays it.
According to the server support, the stream type may have to be set to http and its URL may have to be modified.
Since the web page is plain HTML page and the jQuery Stream is plain JavaScript library, they don't need any server-side support, so choose a
server implementation in WebSocket/HTTP Echo Server according to your preference.
/echo.html
<!DOCTYPE html>
<h1m1>
<head>
<111e>Echo</111e>
<me1a http-equiv="Content-Type" content="text/html; charset=utf-8" />
<scrp1 type="text/javascript" src="./js/jquery-1.4.1.js"></scrp1>
<scrp1 type="text/javascript" src="./js/jquery.stream.js"></scrp1>
<scrp1 type="text/javascript">
$.stream.setup({enableXDR: 1rue);

$(1unc1on() {
$.stream("./echo", {
open: 1unc1on() {
$("#textfield").removeAttr("disabled").focus();
,
message: 1unc1on(event) {
$("<p />").text(event.data).prependTo("#content");
,
error: 1unc1on() {
$("#textfield").attr("disabled", "disabled");
,
close: 1unc1on() {
$("#textfield").attr("disabled", "disabled");

);

$("#textfield").keyup(1unc1on(event) {
1 (event.which === 13 && $.trim(1hs.value)) {
$.stream().send({message: 1hs.value);
1hs.value = "";

);
);
</scrp1>
<s1y1e>
body {paddng: 0; margn: 0; 1on1-1am1y: 'Trebuchet MS','Malgun Gothic'; 1on1-sze: 62.5%; co1or: #333333
#editor {margn: 15px 25px;
#textfield {Wd1h: 100%; hegh1: 28px; 1ne-hegh1: 28px; 1on1-1am1y: 'Trebuchet MS','Malgun Gothic';
border: medium none; border-co1or: #E5E5E5 #DBDBDB #D2D2D2; border-s1y1e: solid; border-Wd1h: 1px;
#content {hegh1: 100%; over11oW-y: auto; paddng: 0 25px;
#content p {margn: 0; paddng: 0; 1on1-sze: 1.3em; co1or: #444444; 1ne-hegh1: 1.7em; Word-Wrap: break-word;
</s1y1e>
</head>
2/24/12 EchoExample - jquery-stream - Echo Example - Comet Streaming JavaScript Library - Google Project
2/6 code.google.com/p/jquery-stream/wiki/EchoExample
</head>
<body>
<dv id="editor">
<npu1 id="textfield" type="text" disabled="disabled" />
</dv>
<dv id="content"></dv>
</body>
</h1m1>
WebSocke/HTTP Echo See
WebSocket/HTTP Echo Server is just a typical echo server which sends back the client's message through ws or http protocol.
See ServerSideProcessing for details about what methods do what.
If you have implemented the server logic using technology or platform not listed, please annotate it and create a issue to append that code to this
wiki.
Jaa - Sele 3.0
The Servlet 3.0 specification includes support for asynchronous processing of request, but there is no support for WebSocket.
The following example runs with any servlet container implementing Servlet 3.0 such as Tomcat 7 and Jetty 8 only via HTTP protocol.
flowersinthesand.example.EchoServlet
package flowersinthesand.example;
mpor1 java.io.IExcep1on;
mpor1 java.io.Prn1Wr1er;
mpor1 java.util.Nap;
mpor1 java.util.UUID;
mpor1 java.util.concurrent.Concurren1hashNap;
mpor1 javax.servlet.AsyncCon1ex1;
mpor1 javax.servlet.AsyncEven1;
mpor1 javax.servlet.AsyncLs1ener;
mpor1 javax.servlet.5erv1e1Excep1on;
mpor1 javax.servlet.annotation.Web5erv1e1;
mpor1 javax.servlet.http.h11p5erv1e1;
mpor1 javax.servlet.http.h11p5erv1e1eques1;
mpor1 javax.servlet.http.h11p5erv1e1esponse;
// RegIs1eIs a seIv1e1 by ne|1y In1Ioduced anno1a1Ion, _kebSeIv1e1
@WebServlet(urlPatterns = "/chat", asyncSupported = 1rue)
pub1c c1ass Echo5erv1e1 ex1ends h11p5erv1e1 {
prva1e s1a1c 1na1 1ong serialVersionUID = -8823775068689773674L;
prva1e Nap<51rng, AsyncCon1ex1> asyncContexts = neW Concurren1hashNap<51rng, AsyncCon1ex1>();
// ET ne1hod Is used 1o open s1Iean
@Override
pro1ec1ed vod doGet(h11p5erv1e1eques1 request, h11p5erv1e1esponse response)
1hroWs 5erv1e1Excep1on, IExcep1on {

// Re]ec1s kebSocke1 openIng handshake
1 ("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
response.sendError(h11p5erv1e1esponse.SC_NOT_IMPLEMENTED);
re1urn;

response.setCharacterEncoding("utf-8");
// Con1en1-Type headeI
response.setContentType("text/plain");
// 4ccess-Con1Io1-411o|-0IIgIn headeI
response.setHeader("Access-Control-Allow-Origin", "*");
Prn1Wr1er writer = response.getWriter();
// Jd
1na1 51rng id = UUID.randomUUID().toString();
writer.prn1(id);
writer.prn1(';');
// PaddIng
1or (n1 i = 0; i < 1024; i++) {
writer.prn1(' ');

writer.prn1(';');
writer.flush();
// S1aI1s asynchIonous node
// 4syncCon1ex1, 4syncLIs1eneI and 4syncEven1 aIe used 1oI asynchIonous opeIa1Ion
1na1 AsyncCon1ex1 ac = request.startAsync();
ac.setTimeout(5 * 60 * 1000);
2/24/12 EchoExample - jquery-stream - Echo Example - Comet Streaming JavaScript Library - Google Project
3/6 code.google.com/p/jquery-stream/wiki/EchoExample
ac.setTimeout(5 * 60 * 1000);
ac.addListener(neW AsyncLs1ener() {
pub1c vod onComplete(AsyncEven1 even1) 1hroWs IExcep1on {
asyncContexts.remove(id);

pub1c vod onTimeout(AsyncEven1 even1) 1hroWs IExcep1on {
asyncContexts.remove(id);

pub1c vod onError(AsyncEven1 even1) 1hroWs IExcep1on {
asyncContexts.remove(id);

pub1c vod onStartAsync(AsyncEven1 even1) 1hroWs IExcep1on {

);
// |anages 4syncCon1ex1 Ins1ances by 1he Id
asyncContexts.put(id, ac);

// P0ST ne1hod Is used 1o hand1e da1a sen1 by useI vIa 1he s1Iean
@Override
pro1ec1ed vod doPost(h11p5erv1e1eques1 request, h11p5erv1e1esponse response)
1hroWs 5erv1e1Excep1on, IExcep1on {
request.setCharacterEncoding("utf-8");
// FInds 4syncCon1ex1 Ins1ance by s1Iean Id
AsyncCon1ex1 ac = asyncContexts.ge1(request.getParameter("metadata.id"));
1 (ac == nu11) {
re1urn;

// C1ose Ieques1 neans 1ha1 bIo|seI c1osed 1hIs s1Iean
1 ("close".equals(request.getParameter("metadata.type"))) {
ac.complete();
re1urn;

51rng message = request.getParameter("message");
Prn1Wr1er writer = ac.getResponse().getWriter();
// Sends nessage
writer.prn1(message.length() + ";" + message + ";");
writer.flush();

Jaa - Sele 3.0 and Je 8


Jetty is a servlet container, implements Servlet 3.0 and also provides WebSocket based on servlet.
Currently, Jetty 8.0.0 M3 does not seem to support new annotations.
web.xml
<Web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<serv1e1>
<serv1e1-name>Echo</serv1e1-name>
<serv1e1-c1ass>flowersinthesand.example.EchoServlet</serv1e1-c1ass>
<async-suppor1ed>true</async-suppor1ed>
</serv1e1>
<serv1e1-mappng>
<serv1e1-name>Echo</serv1e1-name>
<ur1-pa11ern>/echo</ur1-pa11ern>
</serv1e1-mappng>
</Web-app>
flowersinthesand.example.EchoServlet
package flowersinthesand.example;
mpor1 java.io.IExcep1on;
mpor1 java.io.Prn1Wr1er;
mpor1 java.util.Nap;
mpor1 java.util.UUID;
mpor1 java.util.concurrent.Concurren1hashNap;
2/24/12 EchoExample - jquery-stream - Echo Example - Comet Streaming JavaScript Library - Google Project
4/6 code.google.com/p/jquery-stream/wiki/EchoExample
mpor1 javax.servlet.AsyncCon1ex1;
mpor1 javax.servlet.AsyncEven1;
mpor1 javax.servlet.AsyncLs1ener;
mpor1 javax.servlet.5erv1e1Excep1on;
mpor1 javax.servlet.http.h11p5erv1e1eques1;
mpor1 javax.servlet.http.h11p5erv1e1esponse;
mpor1 org.eclipse.jetty.util.ur1Encoded;
mpor1 org.eclipse.jetty.websocket.Web5ocke1;
mpor1 org.eclipse.jetty.websocket.Web5ocke15erv1e1;
// kebSocke1SeIv1e1 ex1endIng |11pSeIv1e1 Is base c1ass
pub1c c1ass Echo5erv1e1 ex1ends Web5ocke15erv1e1 {
prva1e s1a1c 1na1 1ong serialVersionUID = -8823775068689773674L;
prva1e Nap<51rng, AsyncCon1ex1> asyncContexts = neW Concurren1hashNap<51rng, AsyncCon1ex1>();
@Override
pro1ec1ed vod doGet(h11p5erv1e1eques1 request, h11p5erv1e1esponse response)
1hroWs 5erv1e1Excep1on, IExcep1on {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setHeader("Access-Control-Allow-Origin", "*");
Prn1Wr1er writer = response.getWriter();
1na1 51rng id = UUID.randomUUID().toString();
writer.prn1(id);
writer.prn1(';');
1or (n1 i = 0; i < 1024; i++) {
writer.prn1(' ');

writer.prn1(';');
writer.flush();
1na1 AsyncCon1ex1 ac = request.startAsync();
ac.setTimeout(5 * 60 * 1000);
ac.addListener(neW AsyncLs1ener() {
pub1c vod onComplete(AsyncEven1 even1) 1hroWs IExcep1on {
asyncContexts.remove(id);

pub1c vod onTimeout(AsyncEven1 even1) 1hroWs IExcep1on {
asyncContexts.remove(id);

pub1c vod onError(AsyncEven1 even1) 1hroWs IExcep1on {
asyncContexts.remove(id);

pub1c vod onStartAsync(AsyncEven1 even1) 1hroWs IExcep1on {

);
asyncContexts.put(id, ac);

@Override
pro1ec1ed vod doPost(h11p5erv1e1eques1 request, h11p5erv1e1esponse response)
1hroWs 5erv1e1Excep1on, IExcep1on {
request.setCharacterEncoding("utf-8");
AsyncCon1ex1 ac = asyncContexts.ge1(request.getParameter("metadata.id"));
1 (ac == nu11) {
re1urn;

1 ("close".equals(request.getParameter("metadata.type"))) {
ac.complete();
re1urn;

51rng message = request.getParameter("message");
Prn1Wr1er writer = ac.getResponse().getWriter();
writer.prn1(message.length() + ";" + message + ";");
writer.flush();

// |and1es kebSocke1 connec1Ion
@Override
pub1c Web5ocke1 doWebSocketConnect(h11p5erv1e1eques1 request, 51rng protocol) {
// kebSocke1 1oI IeceIvIng 1ex1 nessages
re1urn neW Web5ocke1.nTex1Nessage() {
Connec1on connection;
2/24/12 EchoExample - jquery-stream - Echo Example - Comet Streaming JavaScript Library - Google Project
5/6 code.google.com/p/jquery-stream/wiki/EchoExample
Connec1on connection;
@Override
pub1c vod onOpen(Connec1on connection) {
1hs.connection = connection;

@Override
pub1c vod onClose(n1 closeCode, 51rng message) {

@Override
pub1c vod onMessage(51rng data) {
// 0ecodes queIy s1IIng
ur1Encoded parameters = neW ur1Encoded(data);
1ry {
connection.sendMessage(parameters.getString("message"));
ca1ch (IExcep1on e) {
1hroW neW un1meExcep1on(e);


;

Comment by raghav.c...@gmail.com, May 30, 2011


could you please add comments on what methods do what... ? It would be helpful for newbies like me...
Comment by project member flowersi...@gmail.com, May 31, 2011
Okay, I'll do that. This wiki will be completed after the release of jQuery Stream 1.1.
Comment by mabc...@gmail.com, Jun 10, 2011
So, what's "deprecated" about this example??
Comment by project member flowersi...@gmail.com, Jun 12, 2011
Nothing. I actually meant 'incomplete', not 'deprecated'.
Comment by JonZapir...@gmail.com, Jun 13, 2011
Hi, I have a problem with the timeout, because when the timeout is finished, it creates a new AsyncContext? instance. Why?
Comment by project member flowersi...@gmail.com, Jun 13, 2011
Hello, Because the Stream object will reconnect whenever connection is closed, unless 'reconnect' option is false.
Comment by JonZapir...@gmail.com, Jun 14, 2011
Thanks, I should read everything before asking. Now I have downloaded the version 1.1 and with the same code, in chrome is recived error 501 from
the server.
Comment by project member flowersi...@gmail.com, Jun 14, 2011
Okay, that's because the chrome support WebSocket? but the server doesn't, then you should add type option with a value of http to options as of
1.1.
from http://code.google.com/p/jquery-stream/wiki/API#jQuery.stream
$.stream("./echo", {
type: "http" // ...
});
2/24/12 EchoExample - jquery-stream - Echo Example - Comet Streaming JavaScript Library - Google Project
6/6 code.google.com/p/jquery-stream/wiki/EchoExample
Comment by JonZapir...@gmail.com, Jun 22, 2011
hi! I have a problem with IE8 and XDomainRequest, because when it calls to the server, it generates a new session in the server, so I loose session's
attributes, id, ... Is there any way to preserve the old session?
Comment by project member flowersi...@gmail.com, Jun 23, 2011
XDomainRequest excludes cookies when sending so that the session is not maintained in most cases. For details, see
http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
Instead of using cookies, you can rewrite a URL to maintain session. it can be used when client's cookies are turned off.
With Java Servlet
$.stream("echo;jsessionid=${pageContext.session.id}", {alias: 'echo'});
Comment by JonZapir...@gmail.com, Jun 23, 2011
thanks!! doing that now it's running perfectly!!
Comment by project member flowersi...@gmail.com, Jun 23, 2011
Sure, I recommend you to be aware of session fixation attack.
Comment by Ray.xh.W...@gmail.com, Jul 6, 2011
Hey, any .Net examples that we can learn?
Comment by project member flowersi...@gmail.com, Jul 6, 2011
Sorry, I have never done .Net.
Sign in to add a comment
2011 Google - Terms - Privacy - Project Hosting Help
Powered by Google Project Hosting