java ee 7_ building web applications with websocket, javascript and html5

20
Purpose This tutorial shows you how to create an application that uses the WebSocket API for realtime communication between a client and a server. You learn how to: Create a Java Platform, Enterprise Edition 7 (Java EE 7) application that uses the WebSocket API Use the OnOpen and OnMessage WebSocket lifecycle events to perform different actions on the Java EE 7 application. Define a clientside WebSocket endpoint by using JavaScript Operate on Plain Old Java Objects (POJOs), in realtime, with actions invoked from a web browser client Time to Complete Approximately 1 hour Introduction Modern web applications require more interactivity than ever before for client/server communications. HTTP, however, wasn't built to deliver the kind of interactivity needed today. "Push" or Comet techniques, such as longpolling, emerged as a way to allow a server to push data to a browser. Because these techniques usually rely on HTTP, they present some disadvantages for client/server communications, such as HTTP overhead. These disadvantages result in less efficient communication between the server and the web browser, especially for realtime applications. WebSocket provides an alternative to this limitation by providing bidirectional, fullduplex, realtime, client/server communications. The server can send data to the client at any time. Because WebSocket runs over TCP, it also reduces the overhead of each message. WebSocket also provides greater scalability for messageintensive applications because only one connection per client is used (whereas HTTP creates one request per message). Finally, WebSocket is part of Java EE 7, so you can use other technologies in the Java EE 7 stack. Scenario In this tutorial, you create Java WebSocket Home, a smart home control web application based on Java EE 7. Java WebSocket Home has a user interface for connecting and controlling fictitious devices from a web browser to a Java application. This application provides realtime updates to all clients that are connected to the Java WebSocket Home server. Software Requirements The following is a list of software requirements needed for this tutorial: Download and install the Java EE 7 software development kit (SDK) from http://www.oracle.com/technetwork/java/javaee/downloads/index.html. Download and install the Java NetBeans 7.3.1 integrated development environment (IDE) from http://www.netbeans.org/downloads/index.html. Download and install Oracle GlassFish Server 4.0 from http://www.oracle.com/us/products/middleware/cloudappfoundation/glassfishserver/overview/index.html. Prerequisites Before starting this tutorial, you should have: Knowledge of the Java programming language Basic knowledge of Java EE 7 Basic knowledge of HTML 5, JavaScript, and cascading style sheets (CSS) Introduced as part of the HTML 5 initiative, the WebSocket protocol is a standard web technology that simplifies communication and connection management between clients and a server. By maintaining a constant connection, WebSocket provides fullduplex client/server communication. It also provides a lowlatency, lowlevel communication that works on the underlying TCP/IP connection. The Java API for WebSocket (JSR356) simplifies the integration of WebSocket into Java EE 7 applications. Here are some of the features of the Java API for WebSocket: Annotationdriven programming that allows developers to use POJOs to interact with WebSocket lifecycle events Interfacedriven programming that allows developers to implement interfaces and methods to interact with WebSocket lifecycle events Integration with other Java EE technologies (You can inject objects and Enterprise JavaBeans by using components such as Contexts and Dependency Injection.) In this section, you create a Java EE 7 web application. 1. Open the NetBeans IDE. 2. From the File menu, select New Project. Overview Introduction to the WebSocket API in Java EE 7 Creating a Java EE 7 Project Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

Upload: jean-lopes

Post on 25-Sep-2015

38 views

Category:

Documents


1 download

DESCRIPTION

java ee7 web sockets

TRANSCRIPT

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 1/20

    Purpose

    ThistutorialshowsyouhowtocreateanapplicationthatusestheWebSocketAPIforrealtimecommunicationbetweenaclientandaserver.Youlearnhowto:

    CreateaJavaPlatform,EnterpriseEdition7(JavaEE7)applicationthatusestheWebSocketAPIUsetheOnOpenandOnMessageWebSocketlifecycleeventstoperformdifferentactionsontheJavaEE7application.DefineaclientsideWebSocketendpointbyusingJavaScriptOperateonPlainOldJavaObjects(POJOs),inrealtime,withactionsinvokedfromawebbrowserclient

    TimetoComplete

    Approximately1hour

    Introduction

    Modernwebapplicationsrequiremoreinteractivitythaneverbeforeforclient/servercommunications.HTTP,however,wasn'tbuilttodeliverthekindofinteractivityneededtoday."Push"orComettechniques,suchaslongpolling,emergedasawaytoallowaservertopushdatatoabrowser.BecausethesetechniquesusuallyrelyonHTTP,theypresentsomedisadvantagesforclient/servercommunications,suchasHTTPoverhead.Thesedisadvantagesresultinlessefficientcommunicationbetweentheserverandthewebbrowser,especiallyforrealtimeapplications.

    WebSocketprovidesanalternativetothislimitationbyprovidingbidirectional,fullduplex,realtime,client/servercommunications.Theservercansenddatatotheclientatanytime.BecauseWebSocketrunsoverTCP,italsoreducestheoverheadofeachmessage.WebSocketalsoprovidesgreaterscalabilityformessageintensiveapplicationsbecauseonlyoneconnectionperclientisused(whereasHTTPcreatesonerequestpermessage).Finally,WebSocketispartofJavaEE7,soyoucanuseothertechnologiesintheJavaEE7stack.

    Scenario

    Inthistutorial,youcreateJavaWebSocketHome,asmarthomecontrolwebapplicationbasedonJavaEE7.JavaWebSocketHomehasauserinterfaceforconnectingandcontrollingfictitiousdevicesfromawebbrowsertoaJavaapplication.ThisapplicationprovidesrealtimeupdatestoallclientsthatareconnectedtotheJavaWebSocketHomeserver.

    SoftwareRequirements

    Thefollowingisalistofsoftwarerequirementsneededforthistutorial:

    DownloadandinstalltheJavaEE7softwaredevelopmentkit(SDK)fromhttp://www.oracle.com/technetwork/java/javaee/downloads/index.html.DownloadandinstalltheJavaNetBeans7.3.1integrateddevelopmentenvironment(IDE)fromhttp://www.netbeans.org/downloads/index.html.DownloadandinstallOracleGlassFishServer4.0fromhttp://www.oracle.com/us/products/middleware/cloudappfoundation/glassfishserver/overview/index.html.

    Prerequisites

    Beforestartingthistutorial,youshouldhave:

    KnowledgeoftheJavaprogramminglanguageBasicknowledgeofJavaEE7BasicknowledgeofHTML5,JavaScript,andcascadingstylesheets(CSS)

    IntroducedaspartoftheHTML5initiative,theWebSocketprotocolisastandardwebtechnologythatsimplifiescommunicationandconnectionmanagementbetweenclientsandaserver.Bymaintainingaconstantconnection,WebSocketprovidesfullduplexclient/servercommunication.Italsoprovidesalowlatency,lowlevelcommunicationthatworksontheunderlyingTCP/IPconnection.

    TheJavaAPIforWebSocket(JSR356)simplifiestheintegrationofWebSocketintoJavaEE7applications.

    HerearesomeofthefeaturesoftheJavaAPIforWebSocket:

    AnnotationdrivenprogrammingthatallowsdeveloperstousePOJOstointeractwithWebSocketlifecycleeventsInterfacedrivenprogrammingthatallowsdeveloperstoimplementinterfacesandmethodstointeractwithWebSocketlifecycleeventsIntegrationwithotherJavaEEtechnologies(YoucaninjectobjectsandEnterpriseJavaBeansbyusingcomponentssuchasContextsandDependencyInjection.)

    Inthissection,youcreateaJavaEE7webapplication.

    1. OpentheNetBeansIDE.

    2. FromtheFilemenu,selectNewProject.

    Overview

    Introduction to the WebSocket API in Java EE 7

    Creating a Java EE 7 Project

    JavaEE7:BuildingWebApplicationswithWebSocket,JavaScriptandHTML5

    http://www.oracle.com/us/products/middleware/cloud-app-foundation/glassfish-server/overview/index.htmlhttp://netbeans.org/downloads/http://www.oracle.com/technetwork/java/javaee/downloads/index.htmlhttp://jcp.org/en/jsr/detail?id=356
  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 2/20

    3. IntheNewProjectdialogbox,performthefollowingsteps:

    a. SelectJavaWebfromCategories.b. SelectWebApplicationfromProjects.c. ClickNext.

    4. EnterWebsocketHomeastheprojectnameandclickNext.

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 3/20

    5. IntheNewWebApplicationdialogbox,performthefollowingsteps:

    a. SelectGlassFishServerfromtheServerlist.b. EnterWebsocketHomeasthecontextpath.c. ClickFinish.

    TheWebsocketHomeprojecthasbeencreated.

    6. RightclicktheWebsocketHomeprojectandselectRuntotestyourapplication.

    AbrowserwindowdisplaysaTODOwritecontentmessage.

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 4/20

    YousuccessfullycreatedaJavaEE7webapplicationbyusingNetBeans.

    Inthissection,youcreatetheclassthatcontainsadevice'sattributes.

    1. SelectFile>NewFile.

    2. IntheNewFiledialogbox,performthefollowingsteps:

    a. SelectJavafromCategories.b. SelectJavaClassfromFileTypes.c. ClickNext.

    Creating the Device Model

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 5/20

    3. IntheNewJavaClassdialogbox,performthefollowingsteps:

    a. EnterDeviceastheclassname.b. Enterorg.example.modelasthepackage.c. ClickFinish.

    TheDeviceclassisaddedtotheproject.

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 6/20

    4. AddthefollowingcodetotheDevice.javaclasstodefinetheclassconstructor,anditsgetterandsettermethods:

    ViewCode

    5. SelectFile>Savetosavethefile.

    YousuccessfullycreatedtheDeviceclass.

    Inthissection,youcreateaWebSocketendpoint.

    1. SelectFile>NewFile.

    2. IntheNewFiledialogbox,performthefollowingsteps:

    a. SelectJavafromCategories.b. SelectJavaClassfromFileTypes.c. ClickNext.

    Creating the WebSocket Server Endpoint

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 7/20

    3. IntheNewJavaClassdialogbox,performthefollowingsteps:

    a. EnterDeviceWebSocketServerastheclassname.b. Enterorg.example.websocketasthepackage.c. ClickFinish.

    TheDeviceWebSocketServerclassisaddedtotheproject.

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 8/20

    4. DefinetheWebSocketserverendpointpathbyaddingthefollowingcode:

    5. DefinetheWebSocketlifecycleannotationsbyaddingthefollowingmethodsandimportstotheDeviceWebSocketServerclass:

    TheWebSocketlifecycleannotationsaremappedtoJavamethods.Inthisexample,the@OnOpenannotationismappedtotheopen()methodthe@OnMessageannotationismappedtothehandleMessage()methodthe@OnCloseannotationtotheclose()methodandthe@OnErrorannotationtotheonError()method.

    6. Specifythattheclassisapplicationscopedbyaddingthe@ApplicationScopedannotationandimportingitspackage.

    7. Savethefile.

    YousuccessfullycreatedtheWebSocketserverendpoint.

    Inthissection,youcreateaclassforhandlingthesessionsthatareconnectedtotheserver.

    1. SelectFile>NewFile.

    2. IntheNewFiledialogbox,performthefollowingsteps:

    a. SelectJavafromCategories.b. SelectJavaClassfromFileTypes.c. ClickNext.

    package org.example.websocket;

    import javax.websocket.server.ServerEndpoint;

    @ServerEndpoint("/actions")public class DeviceWebSocketServer { }

    import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/actions")public class DeviceWebSocketServer {

    @OnOpen public void open(Session session) { }

    @OnClose public void close(Session session) { }

    @OnError public void onError(Throwable error) { }

    @OnMessage public void handleMessage(String message, Session session) { }}

    ...import javax.websocket.OnOpen;import javax.websocket.Session;import javax.enterprise.context.ApplicationScoped;

    @ApplicationScoped@ServerEndpoint("/actions")public class DeviceWebSocketServer {...}

    Creating the Session Handler

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 9/20

    3. IntheNewJavaClassdialogbox,performthefollowingsteps:

    a. EnterDeviceSessionHandlerastheclassname.b. Enterorg.example.websocketasthepackage.c. ClickFinish.

    TheDeviceSessionHandlerclassisaddedtotheproject.

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 10/20

    4. Specifythattheclassisapplicationscopedbyaddingthe@ApplicationScopedannotationandimportingitscorrespondingpackage.

    5. DeclareaHashSetforstoringthelistofdevicesaddedtotheapplicationandtheactivesessionsintheapplication,andimporttheirpackages.

    Note:Eachclientconnectedtotheapplicationhasitsownsession.

    6. Definethefollowingmethodsforaddingandremovingsessionstotheserver.

    7. DefinethemethodsthatoperateontheDeviceobject.

    Thesemethodsare:

    addDevice()Addadevicetotheapplication.removeDevice()Removeadevicefromtheapplication.toggleDevice()Togglethedevicestatus.getDevices()Retrievethelistofdevicesandtheirattributes.getDeviceById()Retrieveadevicewithaspecificidentifier.createAddMessage()BuildaJSONmessageforaddingadevicetotheapplication.sendToSession()Sendaneventmessagetoaclient.sendToAllConnectedSessions()Sendaneventmessagetoallconnectedclients.

    package org.example.websocket;

    import javax.enterprise.context.ApplicationScoped;

    @ApplicationScopedpublic class DeviceSessionHandler { }

    package org.example.websocket;

    import javax.enterprise.context.ApplicationScoped;import java.util.HashSet;import java.util.Set;import javax.websocket.Session;import org.example.model.Device;

    @ApplicationScopedpublic class DeviceSessionHandler { private final Set sessions = new HashSet(); private final Set devices = new HashSet();}

    package org.example.websocket;

    ...

    @ApplicationScopedpublic class DeviceSessionHandler { ... public void addSession(Session session) { sessions.add(session); }

    public void removeSession(Session session) { sessions.remove(session); }}

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 11/20

    8. Savethefile.

    Yousuccessfullycreatedthesessionhandler.

    Inthissection,youcreatetheJavaWebSocketHomeuserinterface(UI)byusingHTML5andCSS.

    1. Opentheindex.htmlfile.

    2. Enterthefollowingcodetoaddtheproperelementsforaddinganddisplayingdevicesonthewebbrowserclient.

    ViewCode

    3. Savethefile.

    4. SelectFile>NewFile.

    5. IntheNewFiledialogdialogbox,performthefollowingsteps:

    a. SelectWebfromCategories.b. SelectCascadingStyleSheetfromFileTypes.c. ClickNext.

    package org.example.websocket; ... public class DeviceSessionHandler { ... public List getDevices() { return new ArrayList(devices); }

    public void addDevice(Device device) { }

    public void removeDevice(int id) { }

    public void toggleDevice(int id) { }

    private Device getDeviceById(int id) { return null; }

    private JsonObject createAddMessage(Device device) { return null; }

    private void sendToAllConnectedSessions(JsonObject message) { }

    private void sendToSession(Session session, JsonObject message) { }}

    Rendering the User Interface

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 12/20

    6. IntheNewCascadingStyleSheetdialogbox,performthefollowingsteps:

    a. Enterstyleasthefilename.b. SelectWeb Pagesasthelocation.c. ClickFinish.

    Thestyle.cssfileisaddedtotheproject.

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 13/20

    7. Copythefollowingcodeintothestyle.cssfile.

    ViewCode

    8. Savethefile.

    YousuccessfullycreatedtheUIelementsfortheJavaWebSocketHomeapplication.

    Inthissection,youspecifytheclientendpointbyusingJavaScript.

    1. SelectFile>NewFile.

    2. IntheNewFiledialogbox,performthefollowingsteps:

    a. SelectWebfromCategories.b. SelectJavaScriptFilefromFileTypes.c. ClickNext.

    Creating the WebSocket Client Endpoint

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 14/20

    3. EnterwebsocketasthefilenameandclickFinish.

    Thewebsocket.jsfileisaddedtotheproject.

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 15/20

    Thefileperformsthefollowingactions:

    MapstheWebSocketserverendpointtotheURIdefinedin"CreatingtheWebSocketServerEndpoint".CapturestheJavaScripteventsforadding,removing,andchangingadevice'sstatusandpushesthoseeventstotheWebSocketserver.ThesemethodsareaddDevice(),removeDevice(),andtoggleDevice().TheactionsaresentinJSONmessagestotheWebSocketserver.DefinesacallbackmethodfortheWebSocketonmessageevent.TheonmessageeventcapturestheeventssentfromtheWebSocketserver(inJSON)andprocessesthoseactions.Inthisapplication,theseactionsareusuallyrenderingchangesintheclientUI.TogglesthevisibilityofanHTMLformforaddinganewdevice.

    4. Addthefollowingcodetothewebsocket.jsfile.

    ViewCode

    5. Savethefile.

    YousuccessfullycreatedtheWebSocketclientendpointandthedefinedactionsforhandlingWebSocketeventsintheclient.

    Inthissection,youprocessWebSocketlifecycleeventsintheDeviceWebSocketServerclass.

    1. OpentheDeviceWebSocketServerclass.

    2. InjectaDeviceSessionHandlerobjecttoprocesstheWebSocketlifecycleeventsineachsessionandimportitscorrespondingpackage.

    ViewCode

    3. ProcesstheOnMessageWebSocketlifecycleeventbyaddingthefollowingcodetotheopenmethod.

    ViewCode

    TheOnMessagemethodperformsthefollowingactions:

    Readsdeviceactionsandattributessentfromtheclient.InvokesthesessionhandlertoperformtheproperoperationsonthespecifiedDeviceobject.Inthisapplication,theaddactionsentfromtheclientinvokestheaddDevicemethod,theremoveactioninvokestheremoveDevicemethod,andthetoggleactioninvokesthetoggleDevicemethod.

    4. ProcesstheOnOpenWebSocketeventandaddthemissingimports.

    ViewCode

    TheOnOpeneventreadstheattributessentfromtheclientinJSONandcreatesanewDeviceobjectwiththespecifiedparameters.

    5. ImplementtheOnCloseandOnErroractionsandaddthemissingimports.

    ViewCode

    6. Savethefile.

    YousuccessfullyprocessedWebSocketlifecycleeventsintheDeviceWebSocketServerclass.

    Inthissection,youperformoperationsintheDeviceobjectbyusingtheDeviceSessionHandlerclass.

    1. OpentheDeviceSessionHandler.javaclass.

    2. Defineavariableforstoringthedeviceidentifiersintheserver.

    Processing WebSocket Events in the Server

    Implementing the WebSocket Actions in the Session Handler

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 16/20

    3. AddtheforlooptotheaddSessionmethodtosendthelistofdevicestotheconnectedclient.

    4. ImplementtheaddDevicemethodbyaddingthefollowingcode.

    TheaddDevicemethodperformsthefollowingactions:

    CreatesanewDeviceobjectwiththecurrentvalueofthedeviceIDvariableandtheparametersspecifiedbytheuserintheclient.Sendsamessage,inJSON,toallsessionsoractiveclientsintheWebSocketserver.

    5. ImplementtheremoveDevicemethod.

    TheremoveDevicemethodremovesthedeviceobjectspecifiedbytheuserandsendsamessage,inJSON,toallsessionsthatareactiveintheWebSocketserver.

    6. ImplementthetoggleDevicemethod.

    ThetoggleDevicemethodtogglesthedevicestatusandsendstheeventtoallsessionsthatarestillactiveintheWebSocketserver.

    7. Implementmissingmethods.

    ViewCode

    8. Savethefile.

    YousuccessfullyimplementedtheWebSocketactionsinthesessionhandler.

    ... public class DeviceSessionHandler {

    private int deviceId = 0; private final Set sessions = new HashSet(); private final Set devices = new HashSet(); ...

    }

    public void addSession(Session session) { sessions.add(session); for (Device device : devices) { JsonObject addMessage = createAddMessage(device); sendToSession(session, addMessage); }

    }

    public void addDevice(Device device) { device.setId(deviceId); devices.add(device); deviceId++; JsonObject addMessage = createAddMessage(device); sendToAllConnectedSessions(addMessage); }

    public void removeDevice(int id) { Device device = getDeviceById(id); if (device != null) { devices.remove(device); JsonProvider provider = JsonProvider.provider(); JsonObject removeMessage = provider.createObjectBuilder() .add("action", "remove") .add("id", id) .build(); sendToAllConnectedSessions(removeMessage); } }

    public void toggleDevice(int id) { JsonProvider provider = JsonProvider.provider(); Device device = getDeviceById(id); if (device != null) { if ("On".equals(device.getStatus())) { device.setStatus("Off"); } else { device.setStatus("On"); } JsonObject updateDevMessage = provider.createObjectBuilder() .add("action", "toggle") .add("id", device.getId()) .add("status", device.getStatus()) .build(); sendToAllConnectedSessions(updateDevMessage); } }

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 17/20

    Inthissection,youtesttheJavaWebSocketHomeapplication.

    1. RightclicktheWebsocketHomeprojectandclickRuntobuildanddeploytheproject.

    AWebbrowserdisplaystheJavaWebSocketHomeindexpage.

    2. Openanotherwebbrowserandplaceitnexttothefirstone.

    3. Ineitherwindow,clickAddadevicetodisplaythe"Addanewdevice"form.

    4. Inthe"Addanewdeviceform,"performthefollowingsteps:

    a. EnterMicrowaveasthename.b. SelectApplianceasthetype.c. EnterKitchenasthedescription.d. ClickAdd.

    Testing the Java WebSocket Home Application

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 18/20

    AdeviceisaddedtotheJavaWebSocketHomeserveranditisrenderedinbothwebbrowsers.

    5. Optional:Addmoredevicesofdifferenttypes.

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 19/20

    6. Onanydevice,clickTurnon.

    ThedevicestatuschangestoOffintheserverandallclients.

    7. Onanydevice,clickRemovedevice.

    Thedeviceisremovedfromtheserverandallclients.

    Congratulations!YoucreatedasmarthomecontrolwebapplicationbyusingJavaEE7andtheWebSocketAPI.

    Youalsolearnedhowto:

    DefineaWebSocketserverendpointinaJavaclassbyusingtheWebSocketAPIannotationsSendmessagestoandfromtheclienttotheWebSocketserverinJSONUsetheWebSocketAPIlifecycleannotationstohandleWebSocketevents

    Summary

  • 18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

    http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 20/20

    UsetheWebSocketAPIlifecycleannotationstohandleWebSocketeventsProcessWebSocketlifecycleeventsintheclientbyusingHTML5andJavaScript

    ResourcesFormoreinformationaboutthetopicsinthistutorial,see:

    JavaEE7:NewFeatures,anOracleinstructedcourseonthenewfeaturesofJavaEE7JavaEE7TutorialTheJavaEE7TutorialchapteronWebSocketUsingWebSocketforRealTimeCommunicationinJavaPlatform,EnterpiseEdition7,atutorialaboutWebSocketforJavaEE7.TheAquariumBlogJSR356:JavaAPIforWebSocketWebSocket.org,aWebSocketcommunity"JavaEE7EmbracingHTML5"articleinJavaMagazineTolearnmoreaboutJavaEE7,refertoadditionalOBEsintheOracleLearningLibrary.

    Credits

    LeadCurriculumDeveloper:MiguelSalazarOtherContributors:EduardoMoranchel

    http://docs.oracle.com/javaee/7/tutorial/doc/home.htmhttp://www.websocket.org/http://docs.oracle.com/javaee/7/tutorial/doc/websocket.htm#GKJIQ5https://blogs.oracle.com/theaquarium/http://www.oracle.com/webfolder/technetwork/tutorials/obe/java//WebSocket/WebSocket.htmlhttp://jcp.org/en/jsr/detail?id=356http://www.oraclejavamagazine-digital.com/javamagazine_open/20130506#pg67http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getCourseDesc?dc=D77640GC10http://www.oracle.com/goto/oll