{"id":24283,"date":"2015-06-15T11:00:30","date_gmt":"2015-06-15T08:00:30","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=24283"},"modified":"2019-04-10T13:15:02","modified_gmt":"2019-04-10T10:15:02","slug":"jetty-websocket-example","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/","title":{"rendered":"Jetty WebSocket Example"},"content":{"rendered":"<h2>1.Introduction<\/h2>\n<p>This article is about WebSockets with Jetty. In this example we will give brief information on WebSockets and show how to implement WebSocket Servers and Clients using Jetty WebSocket APIs. In addition to these, an example HTML+JavaScript client interacting with the Server through WebSockets will be provided.<\/p>\n<h2>2.WebSockets<\/h2>\n<p>WebSocket is a standard protocol facilitating full-duplex communication over a single TCP socket. The protocol is designed primarily for Web Browsers and Web Servers however it can be applied to other server-client integration cases.<\/p>\n<p>The concept of WebSockets has been emerged due to the limitations of HTTP. HTTP is a pull based (request-response) protocol; which means that server cannot directly push messages to the client. The alternatives aiming to tackle this problem (TCP sockets, Comet, Long-polling etc.) provide workaround solutions causing side effects of their own.<\/p>\n<p>WebSocket protocol is based on existing web application technologies. A WebSocket connection utilizes the same port with the application server(80 or 8080 for instance), hence it is less likely to be blocked by firewalls.&nbsp;WebSocket connection between client and server is established by a handshake through an HTTP upgrade request. After successful handshake, the protocol is switched from HTTP to WebSocket.<\/p>\n<p>&nbsp;<br \/>\nWebSocket defines two prefixes for the server URI.<\/p>\n<ul>\n<li><b>ws<\/b>: for unsecure connections\n<ul>\n<li>Example: ws:\/\/example.codegeeks.com\/websocketExample<\/li>\n<\/ul>\n<\/li>\n<li><b>wss<\/b>: for secure connections\n<ul>\n<li>Example: wss:\/\/example.codegeeks.com\/websocketExample<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>For the browser based applications, WebSocket protocol support has to be provided by the browser. Currently WebSockets are supported by almost all modern browsers including Chrome, Firefox, Internet Explorer and Safari.<\/p>\n<p>Today WebSockets are widely used in the cases that servers need to push data to the web clients (online gaming, chat).<\/p>\n<h2>3.Jetty WebSocket APIs<\/h2>\n<p>WebSocket technology needs to be supported not only on the browser but also on the server side. Different platforms do have their own implementation for WebSockets both for server and client roles. Jetty is one of the platforms providing WebSocket API for both server and clients sides.<\/p>\n<p>Jetty implements two alternative APIs for WebSocket development:<\/p>\n<p>First of them is the JSR-356 compliant one. JSR-356 is the Java API for WebSocket specification which is included in Java EE 7. The spec defines an annotation based API as well as an listener interface based one.<\/p>\n<p>The other alternative is Jetty&#8217;s own implementation: Jetty WebSocket API. This API had emerged before JSR-356 was released. The programming model of Jetty WebSocket API is very similar to JSR-356 based one. It also provides similar annotations and listener interfaces.<\/p>\n<p>In the following subsections we expand on both alternatives.<\/p>\n<h3>3.1 Alternative 1: Jetty JSR-356 Implementation<\/h3>\n<p>JSR-356 has two different approaches for WebSocket implementation: One is Annotations based whereas the other is Interface based. In the Annotations approach, you have to decorate your POJOs with relevant annotations of the API. In the Interface approach, you need to implement the WebSocket Endpoint interface.<\/p>\n<p>Both approaches are similar. The annotations in the first approach match to the methods to be implemented in the Interface approach. Here we explain only the annotations.<\/p>\n<h4><strong>@ServerEndpoint:<\/strong><\/h4>\n<p>ServerEndpoint is used to annotate a POJO classes as server side WebSockets. The value of the annotation determines the URL path of the WebSocket(similar to the servlet mappings in Java web applications):<\/p>\n<p>An example can be seen below:<\/p>\n<pre class=\"brush:java\"> @ServerEndpoint(value = \"\/example\")\npublic class MySocket{\n\u2026}\n<\/pre>\n<h4><strong>@ClientEndpoint:<\/strong><\/h4>\n<p>ServerEndpoint is used to annotate a POJO classes as client&nbsp;side WebSockets.<\/p>\n<pre class=\"brush:java\">@ClientEndpoint\npublic class MySocket{\n\u2026}<\/pre>\n<h4><strong>@OnOpen:<\/strong><\/h4>\n<p>OnOpen annotates the method that handles the event when a connection is established. JSR-356 does not mandate anything on naming of annotated methods, so we can name our methods as we like.<\/p>\n<pre class=\"brush:java\">@OnOpen\npublic void onSessionOpened(Session session){\n}\n\n<\/pre>\n<p><em>Session<\/em> is the class&nbsp;that encapsulates the Socket connection session.<\/p>\n<h4><strong>@OnMessage:<\/strong><\/h4>\n<p>OnMessage is used to annotate the method that handles the incoming messages.<\/p>\n<p>An example is below:<\/p>\n<pre class=\"brush:java\">@OnMesssage\npublic String onMessageReceived(String message, Session session){\n}\n<\/pre>\n<h4><strong>@OnClose:<\/strong><\/h4>\n<p>We can mark&nbsp;the method that handles the event fired when the socket connection is closed with OnClose annotation. An example usage is below:<\/p>\n<pre class=\"brush:java\">@OnClose\npublic void onClose(Session session, CloseReason closeReason){\n}\n\n<\/pre>\n<p><em>CloseReason<\/em> is a class that encapsulates the termination reason along with a code.<\/p>\n<h4><strong>@OnError:<\/strong><\/h4>\n<p>OnError annotation defines the method&nbsp;that handles exceptions. An example usage is as follows:<\/p>\n<pre class=\"brush:java\">@OnError \npublic void onErrorReceived(Throwable t) {\n}\n<\/pre>\n<p>ServerEndpoint is applicable on server side whereas ClientEndpoint is applicable only on client side. Other annotations are applicable for both sides.<\/p>\n<p>A last remark&nbsp;is that, the signatures (parameter and return types) of the annotated methods must be one of the signatures allowed by JSR-356. The examples presented above are legal according to the spec. <a href=\"https:\/\/docs.oracle.com\/javaee\/7\/api\/javax\/websocket\/package-summary.html\">JavaDoc<\/a> presents the allowed method signatures for each annotation.<\/p>\n<h3>3.2 Alternative 2: Jetty WebSocket API Implementation<\/h3>\n<p>In addition to JSR-356 support, Jetty also provides its own API. The reason that Jetty has two APIs on WebSockets is that JSR-356&nbsp;was released after Jetty had&nbsp;released its own. JSR-356 API is heavily inspired by Jetty&#8217;s.<\/p>\n<p>From the developer\u2019s point of view Jetty API is very similar to the JSR-356\u2019s, with minor differences.<\/p>\n<p>Jetty WebSocket API needs initialization of a Servlet which extends<em> org.eclipse.jetty.websocket.servlet.WebSocketServlet<\/em> class. In JSR-356 implementation this is not needed. In this servlet, we configure the servlet socket class, which resembles the annotated Server Socket class implementation of JSR-356.<\/p>\n<p>In the Example section, we will show how we can configure this server socket at the Servlet implementation.<\/p>\n<p>Jetty API provides three alternative approaches for WebSocket development:<\/p>\n<ul>\n<li>Annotation Based: Similar to JSR-356 annotations<\/li>\n<li>Listener Based: Similar to JSR-356 listeners<\/li>\n<li>Adapter Based: A convenience approach which eases Listener based implementation.<\/li>\n<\/ul>\n<p>The easiest way is the Annotation approach. The annotation names (and classes) are different than JSR-356&#8217;s however&nbsp;they are almost&nbsp;of&nbsp;the same use.<\/p>\n<h4><strong>@WebSocket<\/strong><\/h4>\n<p>This annotation defines that the class is a WebSocket server. It is similar to the <i>@ServletEndpoint<\/i> of JSR-356 but we do not give the endpoint URL here. In addition to this, this annotation is not specific to the server side. Socket clients are also marked with this annotation.<\/p>\n<pre class=\"brush:java\">@WebSocket\npublic class ExampleWebSocket{\n}\n\n<\/pre>\n<h4><strong>@OnWebSocketConnect<\/strong><\/h4>\n<p>This annotation defines that the method to be invoked when a connection is opened. It is similar to <i>@OnOpen <\/i>of JSR-356.<\/p>\n<pre class=\"brush:java\">@OnWebSocketConnect\npublic void onConnect(Session session){\n}\n<\/pre>\n<h4><strong>@OnWebSocketMessage<\/strong><\/h4>\n<p>This annotation defines that the method to be invoked when a message is received. It is similar to <i>@OnMessage <\/i>of JSR-356.<\/p>\n<pre class=\"brush:java\">@OnWebSocketMessage\npublic void onText(Session session, String message){\n}\n<\/pre>\n<h4>@<b>OnWebSocketClose<\/b><\/h4>\n<p>This annotation defines that the method to be invoked when a connection is closed. It is similar to <i>@OnClose <\/i>of JSR-356.<\/p>\n<pre class=\"brush:java\">@OnWebSocketClose\npublic void onClose(Session session, int status, String reason){\n}\n<\/pre>\n<h4>@<b>OnWebSocketError<\/b><\/h4>\n<p>This annotation defines that the method to be invoked when a connection related error is thrown. It is similar to <i>@OnError <\/i>of JSR-356.<\/p>\n<pre class=\"brush:java\">@OnWebSocketError\npublic void onError(Throwable error){\n}\n<\/pre>\n<p>Similar to the JSR-356, the method names are not mandated by Jetty in this approach. The full list of allowed parameter types can be viewed in Jetty <a href=\"http:\/\/download.eclipse.org\/jetty\/9.2.10.v20150310\/apidocs\/org\/eclipse\/jetty\/websocket\/api\/annotations\/package-summary.html\">documentation<\/a>.<\/p>\n<h3>3.3 Which API to Choose?<\/h3>\n<p>Both APIs offer similar features and programming approach. However there are subtle differences.<\/p>\n<p>JSR-356 is specification based and standard. You can port easily your server sockets from Jetty to another Servlet container or Application server as long as the server supports JSR-356. In addition to this, programming with this API is a bit simpler. You do not need to configure a servlet with JSR-356 API. The downside of this alternative is, the documentation on Jetty side is missing and it seems less mature than the second alternative (but that might be just an impression).<\/p>\n<p>Jetty WebSocket API is not standard, so you have to change your code when you change your Servlet Container. In addition to this, you have to code the servlet (some piece of boilerplate code) yourself. But Jetty API is more flexible allowing to easier control timeouts, paths, SSL etc. Another advantage is that, Jetty documentation of its own API is better than Jetty documentation on JSR-356.<\/p>\n<p>At this point, I would humbly recommend using JSR-356 API if simpler configuration matters to you or if portability is a major concern. If you need to configure WebSocket parameters in detail and you do not need to port your WebSocket to another container, I would recommend Jetty WebSocket API.<\/p>\n<p>Of course, this portability issue is only about porting WebSocket code from one container to another (from Jetty to Tomcat for example). WebSocket is a standardized protocol, so any kind of WebSocket client connect to any &nbsp;implementation (JSR compliant or not) server without a problem.<\/p>\n<p>In the following section we will provide examples of both APIs for server and client sides.<\/p>\n<h2>4.Example<\/h2>\n<p>In the example, we will first start with a simple WebSocket Server implementation that gets a text message from the client and echoes back converting the message to uppercase. We will provide both JSR-356 and Jetty API versions of these server side WebSocket implementations.<\/p>\n<p>Later we will move on to the client part. We will implement a Java WebSocket clients interacting with this WebSocket server (again both JSR-356 based and Jetty API versions). Thereafter, we will provide another client example this time with HTML + JavaScript.<\/p>\n<h3>4.1 Environment<\/h3>\n<p>For the example, following programming environment is used:<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<ul>\n<li>For the Jetty WebSocket Server:\n<ul>\n<li>Java 7<\/li>\n<li>Maven 3.x.y<\/li>\n<li>Maven Jetty Plugin<\/li>\n<li>Eclipse Luna as the IDE<\/li>\n<\/ul>\n<\/li>\n<li>For the the Jetty WebSocket Client:\n<ul>\n<li>Java 7<\/li>\n<li>Maven 3.x.y<\/li>\n<li>Eclipse Luna as the IDE<\/li>\n<\/ul>\n<\/li>\n<li>For the HTML WebSocket Client\n<ul>\n<li>A browser supporting WebSockets (Firefox 38.0.5 in this example)<\/li>\n<li>Eclipse Luna as the IDE (used as HTML editor)<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>In this example, we will create a single Maven project in Eclipse and run it as a web application for the servers. The Java&nbsp;clients will be run as console applications and the HTML client will be deployed on the web application.<\/p>\n<h3>4.2 Creating the Maven Project<\/h3>\n<p>In order to create the Maven project on Eclipse, you can follow the steps below:<\/p>\n<ol>\n<li>Go to File -&gt; New -&gt;Other -&gt; Maven Project<\/li>\n<li>Tick &#8220;Create a simple project&#8221; and press \u201cNext\u201d.<\/li>\n<li>Enter groupId as : <em>com.javacodegeeks.snippets.enterprise<\/em><\/li>\n<li>Enter artifactId as : <em>jetty-websocket-example<\/em><\/li>\n<li>Press \u201cFinish\u201d.<\/li>\n<\/ol>\n<p>Now our Maven project is created.<\/p>\n<h3>4.3 Configuring the Maven Dependencies and Jetty Plugin<\/h3>\n<p>In order to configure the project, we need following dependencies:<\/p>\n<p>First we need Jetty dependencies:<\/p>\n<ul>\n<li>org.eclipse.jetty.websocket:jetty-server<\/li>\n<li>org.eclipse.jetty.websocket:jetty-servlet<\/li>\n<\/ul>\n<p>If you are implementing a WebSocket server with JSR-356 API we need:<\/p>\n<ul>\n<li>org.eclipse.jetty.websocket:javax-websocket-server-impl<\/li>\n<\/ul>\n<p>If we choose, Jetty API for WebSocket server we need:<\/p>\n<ul>\n<li>org.eclipse.jetty.websocket:websocket-server<\/li>\n<\/ul>\n<p>For the client side implementation we choose one of the following depending on we choose JSR-356 or the Jetty alternative:<\/p>\n<ul>\n<li>org.eclipse.jetty.websocket:javax-websocket-client-impl<\/li>\n<li>org.eclipse.jetty.websocket:websocket-client<\/li>\n<\/ul>\n<p>The version we have used in this example is <i>9.2.11.v20150529.<\/i><\/p>\n<p>In this example, we have added all of these dependencies to our pom.xml. Depending on the approach you choose, you can remove the unnecessary ones based on your your need.<\/p>\n<pre class=\"brush:xml\"> &lt;dependencies&gt;\n\t\t&lt;!--Jetty dependencies start here --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;jetty-server&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;jetty-servlet&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t\t&lt;!--Jetty dependencies end here --&gt;\n\n\t\t&lt;!--Jetty Websocket server side dependencies start here --&gt;\n\n\n\n\t\t&lt;!--Jetty JSR-356 Websocket server side dependency --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty.websocket&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;javax-websocket-server-impl&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;!--Jetty Websocket API server side dependency --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty.websocket&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;websocket-server&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\n\n\t\t&lt;!--Jetty Websocket server dependencies end here --&gt;\n\t\t\n\t\t&lt;!--Jetty Websocket client side dependencies start here --&gt;\n\n\t\t\n\n\t\t&lt;!--JSR-356 Websocket client side depencency  --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty.websocket&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;javax-websocket-client-impl&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t\t\n\t\t&lt;!--Jetty Websocket API client side dependency --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty.websocket&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;websocket-client&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t\t&lt;!--Jetty Websocket client side dependencies end here --&gt;\n\n\t&lt;\/dependencies&gt;\n<\/pre>\n<p>In order to test our WebSocket server, we use the Maven Jetty plugin. This plugin also has to be added to our pom.xml.<\/p>\n<pre class=\"brush:xml\">&lt;build&gt;\n\t\t&lt;plugins&gt;\n\t\t\t&lt;plugin&gt;\n\t\t\t\t&lt;groupId&gt;org.eclipse.jetty&lt;\/groupId&gt;\n\t\t\t\t&lt;artifactId&gt;jetty-maven-plugin&lt;\/artifactId&gt;\n\t\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t\t&lt;\/plugin&gt;\n\t\t&lt;\/plugins&gt;\n\n\n\t&lt;\/build&gt;\n<\/pre>\n<p>Finally our pom.xml looks like:<\/p>\n<p><span style=\"text-decoration: underline\"><em>pom.xml<\/em><\/span><\/p>\n<pre class=\"brush:xml\">&lt;project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n\txsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\"&gt;\n\t&lt;modelVersion&gt;4.0.0&lt;\/modelVersion&gt;\n\t&lt;groupId&gt;com.javacodegeeks.snippets.enterprise&lt;\/groupId&gt;\n\t&lt;artifactId&gt;jetty-websocket-example&lt;\/artifactId&gt;\n\t&lt;version&gt;0.0.1-SNAPSHOT&lt;\/version&gt;\n\t&lt;packaging&gt;war&lt;\/packaging&gt;\n\t&lt;properties&gt;\n\t\t&lt;jetty.version&gt;9.2.11.v20150529&lt;\/jetty.version&gt;\n\t&lt;\/properties&gt;\n\n\t&lt;build&gt;\n\t\t&lt;plugins&gt;\n\t\t\t&lt;plugin&gt;\n\t\t\t\t&lt;groupId&gt;org.eclipse.jetty&lt;\/groupId&gt;\n\t\t\t\t&lt;artifactId&gt;jetty-maven-plugin&lt;\/artifactId&gt;\n\t\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t\t&lt;\/plugin&gt;\n\t\t&lt;\/plugins&gt;\n\n\n\t&lt;\/build&gt;\n\n\t&lt;dependencies&gt;\n\t\t&lt;!--Jetty dependencies start here --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;jetty-server&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;jetty-servlet&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t\t&lt;!--Jetty dependencies end here --&gt;\n\n\t\t&lt;!--Jetty Websocket server side dependencies start here --&gt;\n\n\n\n\t\t&lt;!--Jetty JSR-356 Websocket server side dependency --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty.websocket&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;javax-websocket-server-impl&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;!--Jetty Websocket API server side dependency --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty.websocket&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;websocket-server&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\n\n\t\t&lt;!--Jetty Websocket server dependencies end here --&gt;\n\t\t\n\t\t&lt;!--Jetty Websocket client side dependencies start here --&gt;\n\n\t\t\n\n\t\t&lt;!--JSR-356 Websocket client side depencency  --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty.websocket&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;javax-websocket-client-impl&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t\t\n\t\t&lt;!--Jetty Websocket API client side dependency --&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.eclipse.jetty.websocket&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;websocket-client&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;${jetty.version}&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t\t&lt;!--Jetty Websocket client side  dependencies end here --&gt;\n\n\t&lt;\/dependencies&gt;\n&lt;\/project&gt;\n<\/pre>\n<h3>4.4 JSR-356 based WebSocket Server Example<\/h3>\n<p>After configuring the pom.xml, you can follow the steps below<\/p>\n<ol>\n<li>Create a POJO class.<\/li>\n<li>Annotate this class with @ServerEndpoint annotation and specify the endpoint value<\/li>\n<li>Implement the methods that handle the OnOpen, OnClose, OnMessage and OnError events.<\/li>\n<li>Annotate these methods with relevant annotations<\/li>\n<\/ol>\n<p>In the example, we will implement a simple WebSocket server that receives a text message , converts it to uppercase and sends it back to the client.<\/p>\n<p>Here we create the class ToUpper356Socket and annotate:<\/p>\n<pre class=\"brush:java\">@ServerEndpoint(\"\/jsr356toUpper\")\npublic class ToUpper356Socket {\n\u2026\n}\n<\/pre>\n<p>Then we implement OnOpen, OnClose, OnMessage methods. We do not have to implement methods for every annotation; so OnError is omitted here.<br \/>\nOur WebSocket server class looks like:<\/p>\n<p><span style=\"text-decoration: underline\"><em>ToUpper356Socket.java<\/em><\/span><\/p>\n<pre class=\"brush:java\"> \npackage com.javacodegeeks.snippets.enterprise.jettywebsocket.jsr356.server;\n\nimport java.io.IOException;\n\nimport javax.websocket.CloseReason;\nimport javax.websocket.OnClose;\nimport javax.websocket.OnMessage;\nimport javax.websocket.OnOpen;\nimport javax.websocket.Session;\nimport javax.websocket.server.ServerEndpoint;\n\n@ServerEndpoint(\"\/jsr356toUpper\")\npublic class ToUpper356Socket {\n\n\t@OnOpen\n\tpublic void onOpen(Session session) {\n\t\tSystem.out.println(\"WebSocket opened: \" + session.getId());\n\t}\n\t@OnMessage\n\tpublic void onMessage(String txt, Session session) throws IOException {\n\t\tSystem.out.println(\"Message received: \" + txt);\n\t\tsession.getBasicRemote().sendText(txt.toUpperCase());\n\t}\n\n\t@OnClose\n\tpublic void onClose(CloseReason reason, Session session) {\n\t\tSystem.out.println(\"Closing a WebSocket due to \" + reason.getReasonPhrase());\n\n\t}\n}\n\n<\/pre>\n<p><em>javax.websocket.Session<\/em> is an important class that encapsulates WebSocket connection information. We can access client information, connection status etc. through the instances of this&nbsp;<em>Session<\/em> class.<\/p>\n<p>In order to send messages to the remote party, we use the session object again.<\/p>\n<pre class=\"brush:java\"> session.getBasicRemote().sendText(\u201cecho\u201d);\n<\/pre>\n<p>sendText() is a method to send simple text messages to the client. There are also other methods to pass byte arrays or JSON objects to the remote party.<\/p>\n<p>When we are done with coding the <em>WebSocket<\/em> server, we can run it via Jetty maven plugin with the following command:<\/p>\n<pre class=\"brush:bash\"> mvn jetty:run<\/pre>\n<p>Once Jetty is up, our websocket starts to listen connections on:<\/p>\n<p>ws:\/\/localhost:8080\/jsr356toUpper<\/p>\n<h3>4.5 JSR-356 based WebSocket Client Example<\/h3>\n<p>Now we are going to implement the WebSocket client code. Creating a client WebSocket with JSR-356 API is similar to the creating the server side socket:<\/p>\n<ol>\n<li>Create a POJO class.<\/li>\n<li>Annotate this class with <em>@ClientEndpoint&nbsp;<\/em>annotation.<\/li>\n<li>Implement the methods that handle the OnOpen, OnClose, OnMessage and OnError events.<\/li>\n<li>Annotate these methods with relevant annotations.<\/li>\n<\/ol>\n<p>The Session object and message sending is the same as the Server side socket. You can see an example code below:<\/p>\n<p><span style=\"text-decoration: underline\"><em>ToUpper356ClientSocket.java<\/em><\/span><\/p>\n<pre class=\"brush:java\"> \npackage com.javacodegeeks.snippets.enterprise.jettywebsocket.jsr356.client;\n\nimport java.io.IOException;\nimport java.util.concurrent.CountDownLatch;\n\nimport javax.websocket.ClientEndpoint;\nimport javax.websocket.CloseReason;\nimport javax.websocket.OnClose;\nimport javax.websocket.OnMessage;\nimport javax.websocket.OnOpen;\nimport javax.websocket.Session;\n\n@ClientEndpoint\npublic class ToUpper356ClientSocket {\n\n\tCountDownLatch latch = new CountDownLatch(1);\n\tprivate Session session;\n\n\t@OnOpen\n\tpublic void onOpen(Session session) {\n\t\tSystem.out.println(\"Connected to server\");\n\t\tthis.session = session;\n\t\tlatch.countDown();\n\t}\n\n\t@OnMessage\n\tpublic void onText(String message, Session session) {\n\t\tSystem.out.println(\"Message received from server:\" + message);\n\t}\n\n\t@OnClose\n\tpublic void onClose(CloseReason reason, Session session) {\n\t\tSystem.out.println(\"Closing a WebSocket due to \" + reason.getReasonPhrase());\n\t}\n\n\tpublic CountDownLatch getLatch() {\n\t\treturn latch;\n\t}\n\n\tpublic void sendMessage(String str) {\n\t\ttry {\n\t\t\tsession.getBasicRemote().sendText(str);\n\t\t} catch (IOException e) {\n\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}\n\n<\/pre>\n<p>You might have noticed that there is a CountDownLatch that is counted down when the connection is open. This latch is only for convenience in order to block other part of the client code before the connection is open. In addition to this, we added a&nbsp;<em>public void sendMessage()<\/em> method to send messages to the server.[ulp id=&#8217;xFHGZUmgemwCMrAR&#8217;]<\/p>\n<p>Until now, we have created the <em>WebSocket<\/em>; the missing part is the code driving the client and initiating the contact. The snippet to initiate the connection can be seen below:<\/p>\n<pre class=\"brush:java\"> \n...\nString dest = \"ws:\/\/localhost:8080\/jsr356toUpper\";\nToUpper356ClientSocket socket = new ToUpper356ClientSocket();\nWebSocketContainer container = ContainerProvider.getWebSocketContainer();\ncontainer.connectToServer(socket, new URI(dest));\n...\n<\/pre>\n<p>In order to keep things simple in scope of this example, we created a simple main class&nbsp;to&nbsp;drive this client WebSocket.<\/p>\n<p><span style=\"text-decoration: underline\"><em>WebSocket356ClientMain.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.snippets.enterprise.jettywebsocket.jsr356.client;\n\nimport java.net.URI;\n\nimport javax.websocket.ContainerProvider;\nimport javax.websocket.WebSocketContainer;\n\nimport org.eclipse.jetty.websocket.client.ClientUpgradeRequest;\n\npublic class WebSocket356ClientMain {\n\n\tpublic static void main(String[] args) {\n\t\n\t\ttry {\n\n\t\t\tString dest = \"ws:\/\/localhost:8080\/jsr356toUpper\";\n\t\t\tToUpper356ClientSocket socket = new ToUpper356ClientSocket();\n\t\t\tWebSocketContainer container = ContainerProvider.getWebSocketContainer();\n\t\t\tcontainer.connectToServer(socket, new URI(dest));\n\n\t\t\tsocket.getLatch().await();\n\t\t\tsocket.sendMessage(\"echo356\");\n\t\t\tsocket.sendMessage(\"test356\");\n\t\t\tThread.sleep(10000l);\n\n\t\t} catch (Throwable t) {\n\t\t\tt.printStackTrace();\n\t\t}\n\t}\n}\n<\/pre>\n<p>Here we have established the connection and waited until the connection is set up. Then we have sent two messages and terminated.<\/p>\n<p>The console output is below:<\/p>\n<pre class=\"brush:bash\">Connected to server\nMessage received from server:ECHO356\nMessage received from server:TEST356\nClosing a WebSocket due to Shutdown\n<\/pre>\n<p>On the server side, we observe the following output:<\/p>\n<pre class=\"brush:bash\">WebSocket opened: websocket-1\nMessage received: echo356\nMessage received: test356\nClosing a WebSocket due to Shutdown\n<\/pre>\n<p>&nbsp;<\/p>\n<h3>4.6 Jetty WebSocket Server Example<\/h3>\n<p>Programming a WebSocket server with the Jetty API is not much different:<\/p>\n<ol>\n<li>Create a POJO class.<\/li>\n<li>Annotate this class with @WebSocket annotation.<\/li>\n<li>Implement the methods that handle the OnWebSocketConnect, OnWebSocketClose, OnWebSocketMessage and OnWebSocketError events.<\/li>\n<li>Annotate these methods with relevant annotations<\/li>\n<\/ol>\n<p>Now we will implement the same WebSocket that converts&nbsp;client messages to upper case.<\/p>\n<p>Our POJO initially looks like:<\/p>\n<pre class=\"brush:java\">@WebSocket\npublic class ToUpperWebSocket {\n}\n<\/pre>\n<p>After the methods and annotations are added, it becomes:<\/p>\n<p><span style=\"text-decoration: underline\"><em>ToUpperWebSocket.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.snippets.enterprise.jettywebsocket.jetty.server;\n\nimport java.io.IOException;\n\nimport org.eclipse.jetty.websocket.api.Session;\nimport org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;\nimport org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;\nimport org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;\nimport org.eclipse.jetty.websocket.api.annotations.WebSocket;\n\n@WebSocket\npublic class ToUpperWebSocket {\n\n\t@OnWebSocketMessage\n\tpublic void onText(Session session, String message) throws IOException {\n\t\tSystem.out.println(\"Message received:\" + message);\n\t\tif (session.isOpen()) {\n\t\t\tString response = message.toUpperCase();\n\t\t\tsession.getRemote().sendString(response);\n\t\t}\n\t}\n\n\t@OnWebSocketConnect\n\tpublic void onConnect(Session session) throws IOException {\n\t\tSystem.out.println(session.getRemoteAddress().getHostString() + \" connected!\");\n\t}\n\n\t@OnWebSocketClose\n\tpublic void onClose(Session session, int status, String reason) {\n\t\tSystem.out.println(session.getRemoteAddress().getHostString() + \" closed!\");\n\t}\n\n}\n<\/pre>\n<p>Here the session object is of type <em>org.eclipse.jetty.websocket.api.Session<\/em> and sending messages to the client is performed with following method call:<\/p>\n<pre class=\"brush:java\">session.getRemote().sendString(\"echo!\");\n<\/pre>\n<p>As you see, there is not much difference between JSR-356 API and Jetty\u2019s up-to here except we did not configure the URL path in the WebSocket class. Now we will configure it via a Servlet.<\/p>\n<p>The main difference of Jetty WebSocket API is that we have to implement a Servlet extending WebSocketServlet class. In this servlet, we define the URL pattern to be matched and we configure WebSocket class handling the requests to this URL. A minimal servlet implementation is here:<\/p>\n<p><span style=\"text-decoration: underline\"><em>ToUpperWebSocketServlet.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.snippets.enterprise.jettywebsocket.jetty.server;\n\nimport javax.servlet.annotation.WebServlet;\n\nimport org.eclipse.jetty.websocket.servlet.WebSocketServlet;\nimport org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;\n\n@WebServlet(urlPatterns=\"\/toUpper\")\npublic class ToUpperWebSocketServlet  extends WebSocketServlet{\n\n\t@Override\n\tpublic void configure(WebSocketServletFactory factory) {\n\t\t\n\t      factory.register(ToUpperWebSocket.class);\n\t\t\n\t}\n\n}\n<\/pre>\n<p>In this servlet, we define the URL path for the server and register our <em>ToUpperWebSocket<\/em> for this Servlet.<\/p>\n<p>Once we implement the servlet, we can run <em>mvn jetty:run<\/em> again.<\/p>\n<p>Now we can access our socket on:<\/p>\n<p>ws:\/\/localhost:8080\/toUpper<\/p>\n<h3>4.7 Jetty WebSocket Client Example<\/h3>\n<p>Here we are going to implement the WebSocket client code with the Jetty API. Steps are below:<\/p>\n<ol>\n<li>Create a POJO class.<\/li>\n<li>Annotate this class with @WebSocket annotation.<\/li>\n<li>Implement the methods that handle the OnWebSocketConnect, OnWebSocketClose, OnWebSocketMessage and OnWebSocketError events.<\/li>\n<li>Annotate these methods with relevant annotations<\/li>\n<\/ol>\n<p>The Session object and message sending is the same as the Server side socket. You can see an example client side WebSocket code below:<br \/>\n<span style=\"text-decoration: underline\"><em>ToUpperClientSocket.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.snippets.enterprise.jettywebsocket.jetty.client;\n\nimport java.io.IOException;\nimport java.util.concurrent.CountDownLatch;\n\nimport org.eclipse.jetty.websocket.api.Session;\nimport org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;\nimport org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;\nimport org.eclipse.jetty.websocket.api.annotations.WebSocket;\n\n@WebSocket\npublic class ToUpperClientSocket {\n\n\tprivate Session session;\n\t\n\tCountDownLatch latch= new CountDownLatch(1);\n\n\t@OnWebSocketMessage\n\tpublic void onText(Session session, String message) throws IOException {\n\t\tSystem.out.println(\"Message received from server:\" + message);\n\t}\n\n\t@OnWebSocketConnect\n\tpublic void onConnect(Session session) {\n\t\tSystem.out.println(\"Connected to server\");\n\t\tthis.session=session;\n\t\tlatch.countDown();\n\t}\n\t\n\tpublic void sendMessage(String str) {\n\t\ttry {\n\t\t\tsession.getRemote().sendString(str);\n\t\t} catch (IOException e) {\n\t\t\t\/\/ TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic CountDownLatch getLatch() {\n\t\treturn latch;\n\t}\n\n}\n\n<\/pre>\n<p>Again we have a CountDownLatch as in the JSR-356 client socket for sycnhronization purposes.<\/p>\n<p>The code that starts connection for the client is below:<\/p>\n<pre class=\"brush:java\">...\nString dest = \"ws:\/\/localhost:8080\/jsr356toUpper\";\nWebSocketClient client = new WebSocketClient();\nToUpperClientSocket socket = new ToUpperClientSocket();\nclient.start();\n...\n<\/pre>\n<p>A simple main class establishing a connection with this server socket is below:<\/p>\n<p><span style=\"text-decoration: underline\"><em>WebSocketClientMain.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.snippets.enterprise.jettywebsocket.jetty.client;\n\nimport java.net.URI;\n\nimport org.eclipse.jetty.websocket.client.ClientUpgradeRequest;\nimport org.eclipse.jetty.websocket.client.WebSocketClient;\n\npublic class WebSocketClientMain {\n\n\tpublic static void main(String[] args) {\n\t\tString dest = \"ws:\/\/localhost:8080\/jsr356toUpper\";\n\t\tWebSocketClient client = new WebSocketClient();\n\t\ttry {\n\t\t\t\n\t\t\tToUpperClientSocket socket = new ToUpperClientSocket();\n\t\t\tclient.start();\n\t\t\tURI echoUri = new URI(dest);\n\t\t\tClientUpgradeRequest request = new ClientUpgradeRequest();\n\t\t\tclient.connect(socket, echoUri, request);\n\t\t\tsocket.getLatch().await();\n\t\t\tsocket.sendMessage(\"echo\");\n\t\t\tsocket.sendMessage(\"test\");\n\t\t\tThread.sleep(10000l);\n\n\t\t} catch (Throwable t) {\n\t\t\tt.printStackTrace();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tclient.stop();\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n}\n\n<\/pre>\n<p>The console output is below:<\/p>\n<pre class=\"brush:bash\">Connected to server\nMessage received from server:ECHO\nMessage received from server:TEST\n<\/pre>\n<h3>4.8 HTML Client Example<\/h3>\n<p>Java based client for a WebSocket is convenient for some cases but the core use of WebSockets is ability to push data from servers to browsers. In this part, we will create a simple HTML page connecting to the WebSocket server in order to demonstrate browser to server integration.<\/p>\n<p>This example page has three functionalities:<\/p>\n<ol>\n<li>User shall connect to the server.<\/li>\n<li>User shall send messages to the server.<\/li>\n<li>User shall see the received messages on the server.<\/li>\n<\/ol>\n<p>On this purpose, there are two buttons on the page. One is to CONNECT, one is to SEND messages. In addition to these, there is a text input area and an output div in the HTML page.<\/p>\n<p>When the user clicks the CONNECT button, following JavaScript code executes connecting to the server.<\/p>\n<p>The connection code is as follows:<\/p>\n<pre class=\"brush:javascript\">function connect() {\n\t\t\/\/ open the connection if one does not exist\n\t\tif (webSocket !== undefined\n\t\t\t\t&amp;&amp; webSocket.readyState !== WebSocket.CLOSED) {\n\t\t\treturn;\n\t\t}\n\t\t\/\/ Create a websocket\n\t\twebSocket = new WebSocket(\"ws:\/\/localhost:8080\/toUpper\");\n\n\t\twebSocket.onopen = function(event) {\n\t\t\tupdateOutput(\"Connected!\");\n\t\t\tconnectBtn.disabled = true;\n\t\t\tsendBtn.disabled = false;\n\n\t\t};\n\n\t\twebSocket.onmessage = function(event) {\n\t\t\tupdateOutput(event.data);\n\t\t};\n\n\t\twebSocket.onclose = function(event) {\n\t\t\tupdateOutput(\"Connection Closed\");\n\t\t\tconnectBtn.disabled = false;\n\t\t\tsendBtn.disabled = true;\n\t\t};\n\t}\n<\/pre>\n<p>After successful connection, <em>onopen<\/em> function of the WebSocket is called. In the example, it is implemented to update the output panel.<\/p>\n<p>Everytime a message is received, the output is updated with the message. This is defined implementing the <em>onmessage<\/em> function of the of the websocket object.<\/p>\n<p>When the connection is terminated for any reason, the output is updated again. This behavior is realized implementing the <em>onclose<\/em> function of the websocket.<\/p>\n<p>When the user types something in the input text and presses the SEND button, the input text is sent to the server via the WebSocket. The snippet on this purpose is as below:<\/p>\n<pre class=\"brush:javascript\">function send() {\n\t\tvar text = document.getElementById(\"input\").value;\n\t\twebSocket.send(text);\n\t}\n<\/pre>\n<p>&nbsp;<\/p>\n<p>As you see, unlike HTTP the type of interaction with WebSockets is duplex; we can simultaneously send and receive data. In HTTP, we would have to initiate an HTTP request and wait for the response to receive data from the server.<\/p>\n<p>The full code of the HTML page is below:<\/p>\n<pre class=\"brush:html\">&lt;html&gt;\n&lt;body&gt;\n\t&lt;div&gt;\n\t\t&lt;input type=\"text\" id=\"input\" \/&gt;\n\t&lt;\/div&gt;\n\t&lt;div&gt;\n\t\t&lt;input type=\"button\" id=\"connectBtn\" value=\"CONNECT\"\n\t\t\tonclick=\"connect()\" \/&gt; &lt;input type=\"button\" id=\"sendBtn\"\n\t\t\tvalue=\"SEND\" onclick=\"send()\" disabled=\"true\" \/&gt;\n\t&lt;\/div&gt;\n\t&lt;div id=\"output\"&gt;\n\t\t&lt;p&gt;Output&lt;\/p&gt;\n\t&lt;\/div&gt;\n&lt;\/body&gt;\n\n&lt;script type=\"text\/javascript\"&gt;\n\tvar webSocket;\n\tvar output = document.getElementById(\"output\");\n\tvar connectBtn = document.getElementById(\"connectBtn\");\n\tvar sendBtn = document.getElementById(\"sendBtn\");\n\n\tfunction connect() {\n\t\t\/\/ open the connection if one does not exist\n\t\tif (webSocket !== undefined\n\t\t\t\t&amp;&amp; webSocket.readyState !== WebSocket.CLOSED) {\n\t\t\treturn;\n\t\t}\n\t\t\/\/ Create a websocket\n\t\twebSocket = new WebSocket(\"ws:\/\/localhost:8080\/toUpper\");\n\n\t\twebSocket.onopen = function(event) {\n\t\t\tupdateOutput(\"Connected!\");\n\t\t\tconnectBtn.disabled = true;\n\t\t\tsendBtn.disabled = false;\n\n\t\t};\n\n\t\twebSocket.onmessage = function(event) {\n\t\t\tupdateOutput(event.data);\n\t\t};\n\n\t\twebSocket.onclose = function(event) {\n\t\t\tupdateOutput(\"Connection Closed\");\n\t\t\tconnectBtn.disabled = false;\n\t\t\tsendBtn.disabled = true;\n\t\t};\n\t}\n\n\tfunction send() {\n\t\tvar text = document.getElementById(\"input\").value;\n\t\twebSocket.send(text);\n\t}\n\n\tfunction closeSocket() {\n\t\twebSocket.close();\n\t}\n\n\tfunction updateOutput(text) {\n\t\toutput.innerHTML += \"&lt;br\/&gt;\" + text;\n\t}\n&lt;\/script&gt;\n&lt;\/html&gt;\n\n<\/pre>\n<p>You can see a screenshot from the web client here:<\/p>\n<p><figure id=\"attachment_24417\" aria-describedby=\"caption-attachment-24417\" style=\"width: 574px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/websocket.jpg\"><img decoding=\"async\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/websocket.jpg\" alt=\"Web Client GUI\" width=\"574\" height=\"452\" class=\"size-full wp-image-24417\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/websocket.jpg 574w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/websocket-300x236.jpg 300w\" sizes=\"(max-width: 574px) 100vw, 574px\" \/><\/a><figcaption id=\"caption-attachment-24417\" class=\"wp-caption-text\">Web Client GUI<\/figcaption><\/figure><\/p>\n<p>Please note that the HTML +JavaScript code are for simple demonstration purpose only. There are many better development practices and libraries for front-end development.<\/p>\n<h2>5.Conclusion<\/h2>\n<p>WebSocket is a technology tackling the shortcomings of the HTTP for bidirectional duplex communication. It is a trending topic that is becoming more widespread. In this post, we have strived to provide brief information on WebSockets and we have provided example Server and Client side implementations of WebSockets using WebSocket API of Jetty.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here : <a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/jetty-websocket-example.zip\"><strong>JettyWebSocketExample<\/strong> <\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>1.Introduction This article is about WebSockets with Jetty. In this example we will give brief information on WebSockets and show how to implement WebSocket Servers and Clients using Jetty WebSocket APIs. In addition to these, an example HTML+JavaScript client interacting with the Server through WebSockets will be provided. 2.WebSockets WebSocket is a standard protocol facilitating &hellip;<\/p>\n","protected":false},"author":54,"featured_media":1239,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18],"tags":[971],"class_list":["post-24283","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-jetty","tag-websocket"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Jetty WebSocket Example - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"1.Introduction This article is about WebSockets with Jetty. In this example we will give brief information on WebSockets and show how to implement\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Jetty WebSocket Example - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"1.Introduction This article is about WebSockets with Jetty. In this example we will give brief information on WebSockets and show how to implement\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2015-06-15T08:00:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-04-10T10:15:02+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Ibrahim Tasyurt\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@itasyurt\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Ibrahim Tasyurt\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"24 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/\"},\"author\":{\"name\":\"Ibrahim Tasyurt\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/b2b2c4a3762c4d2e0072b831fb6900f5\"},\"headline\":\"Jetty WebSocket Example\",\"datePublished\":\"2015-06-15T08:00:30+00:00\",\"dateModified\":\"2019-04-10T10:15:02+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/\"},\"wordCount\":2990,\"commentCount\":7,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg\",\"keywords\":[\"websocket\"],\"articleSection\":[\"jetty\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/\",\"name\":\"Jetty WebSocket Example - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg\",\"datePublished\":\"2015-06-15T08:00:30+00:00\",\"dateModified\":\"2019-04-10T10:15:02+00:00\",\"description\":\"1.Introduction This article is about WebSockets with Jetty. In this example we will give brief information on WebSockets and show how to implement\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Enterprise Java\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/enterprise-java\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"jetty\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/enterprise-java\/jetty\/\"},{\"@type\":\"ListItem\",\"position\":5,\"name\":\"Jetty WebSocket Example\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/b2b2c4a3762c4d2e0072b831fb6900f5\",\"name\":\"Ibrahim Tasyurt\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/Ibrahim-Tasyurt-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/Ibrahim-Tasyurt-96x96.jpg\",\"caption\":\"Ibrahim Tasyurt\"},\"description\":\"Ibrahim is a Senior Software Engineer residing in Ankara,Turkey. He holds BSc and MS degrees in Computer Engineering from Middle East Technical University(METU). Throughout his professional carrier, he has worked in Enterprise Web Application projects for public sector and telecommunications domains. Java EE, Web Services and Enterprise Application Integration are the areas he is primarily involved with.\",\"sameAs\":[\"http:\/\/www.javacodegeeks.com\/\",\"https:\/\/x.com\/itasyurt\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/ibrahim-tasyurt\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Jetty WebSocket Example - Java Code Geeks","description":"1.Introduction This article is about WebSockets with Jetty. In this example we will give brief information on WebSockets and show how to implement","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/","og_locale":"en_US","og_type":"article","og_title":"Jetty WebSocket Example - Java Code Geeks","og_description":"1.Introduction This article is about WebSockets with Jetty. In this example we will give brief information on WebSockets and show how to implement","og_url":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2015-06-15T08:00:30+00:00","article_modified_time":"2019-04-10T10:15:02+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg","type":"image\/jpeg"}],"author":"Ibrahim Tasyurt","twitter_card":"summary_large_image","twitter_creator":"@itasyurt","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Ibrahim Tasyurt","Est. reading time":"24 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/"},"author":{"name":"Ibrahim Tasyurt","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/b2b2c4a3762c4d2e0072b831fb6900f5"},"headline":"Jetty WebSocket Example","datePublished":"2015-06-15T08:00:30+00:00","dateModified":"2019-04-10T10:15:02+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/"},"wordCount":2990,"commentCount":7,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg","keywords":["websocket"],"articleSection":["jetty"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/","url":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/","name":"Jetty WebSocket Example - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg","datePublished":"2015-06-15T08:00:30+00:00","dateModified":"2019-04-10T10:15:02+00:00","description":"1.Introduction This article is about WebSockets with Jetty. In this example we will give brief information on WebSockets and show how to implement","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/codehaus-jetty-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/enterprise-java\/jetty\/jetty-websocket-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Enterprise Java","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/enterprise-java\/"},{"@type":"ListItem","position":4,"name":"jetty","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/enterprise-java\/jetty\/"},{"@type":"ListItem","position":5,"name":"Jetty WebSocket Example"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/b2b2c4a3762c4d2e0072b831fb6900f5","name":"Ibrahim Tasyurt","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/Ibrahim-Tasyurt-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/06\/Ibrahim-Tasyurt-96x96.jpg","caption":"Ibrahim Tasyurt"},"description":"Ibrahim is a Senior Software Engineer residing in Ankara,Turkey. He holds BSc and MS degrees in Computer Engineering from Middle East Technical University(METU). Throughout his professional carrier, he has worked in Enterprise Web Application projects for public sector and telecommunications domains. Java EE, Web Services and Enterprise Application Integration are the areas he is primarily involved with.","sameAs":["http:\/\/www.javacodegeeks.com\/","https:\/\/x.com\/itasyurt"],"url":"https:\/\/examples.javacodegeeks.com\/author\/ibrahim-tasyurt\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/24283","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/54"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=24283"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/24283\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/1239"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=24283"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=24283"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=24283"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}