web sockets
References:
Web sockets provide two way (full duplex) communication between the client and the server over a single connection
Web Sockets are useful for:
Frequent polling - client makes frequent requests to the server asking for new data (AJAX)
- Professional Java for Web Applications
Web sockets provide two way (full duplex) communication between the client and the server over a single connection
Web Sockets are useful for:
- trading applications
- social applications, chats
- sending notifications
- gaming applications
Frequent polling - client makes frequent requests to the server asking for new data (AJAX)
- An enormous number of wasted requests could be made and replied to needlessly
Long Polling - client makes request to the server asking for new data, but the server does not reply and holds the connection until it had new data to send.
- What if the browser has new data to send to the server before the server responds? The browser must either make a separate, parallel request, or it must terminate the current request (from which the server must recover gracefully) and begin another one.
- Connection timeouts are built into the TCP and HTTP specifications. Because of this, the server and client must periodically close and re-establish a connection. Sometimes the connection closes as often as every 60 seconds, although some implementations have been successful at holding a connection for several minutes.
- A connection limit mandate exists in the HTTP/1.1 specification. Browsers must permit no more than two simultaneous connections to any given hostname. If one connection is constantly tied up waiting for data to be pushed from the server, it cuts in half the number of connections that can be used to fetch web pages, graphics, and other resources from the server.
Web Sockets is different protocol than HTTP, lays on top of TCP
Web Socket Handshake
Either:
Client makes an HTTP request with Connection: Upgrade header and a list of protocols it wants to
If Server supports any of the requested protocols, it responds with
HTTP 101 and the first protocol in the list that it supports
Or:
Client requests a resource on the server that requires upgrade
server responds with Upgrade Required header
very first very simple java web socket
Create a dynamic web project just like you did before, name it WebSockets so that our URLs match
You should not need any dependencies
Create a Java Class:
You should not need any dependencies
Create a Java Class:
import java.io.IOException; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/demo1") public class WebSocketDemo1 { @OnOpen public void greeting(Session session) { try { System.out.println("got new connection:" + session.getId()); session.getBasicRemote().sendText("Hello from the server!"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } session.getBasicRemote().sendText("Hello Again!"); } catch (IOException e) { e.printStackTrace(); } } }
Add your project to Tomcat
Your WebSocket application should be ready to use and accessible at ws://localhost:8080/WebSockets/demo1
Let's write a small JavaScript client now that can communicate with the websocket
Your WebSocket application should be ready to use and accessible at ws://localhost:8080/WebSockets/demo1
Let's write a small JavaScript client now that can communicate with the websocket
<html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Demo1 WebSocket</title> </head> <body> <script type="text/javascript"> var wsUri = "ws://localhost:8080/WebSockets/demo1"; websocket = new WebSocket(wsUri); websocket.onopen = function() { $("#js").append("Connection Established<br/>"); }; websocket.onmessage = function(event) { $("#js").append("Message Received <br/>"); $("#messages").append(event.data+"<br/>"); }; websocket.onclose = function(event) { $("#js").append("Connection Closed <br/>"); }; </script> <h3>Messages should appear here:</h3> <div id="messages"></div> <h3>Log from the JavaScript:</h3> <div id="js"></div> </body> </html>
sending messages from client
demo2.html
<html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Demo2 WebSocket</title> <script> $(document).ready(function(){ $("#wsbutton").click(function(){ websocket.send($("#wsmessage").val()); }); }); </script> </head> <body> <script type="text/javascript"> var wsUri = "ws://localhost:8080/WebSockets/demo2"; websocket = new WebSocket(wsUri); websocket.onopen = function() { $("#js").append("Connection Established<br/>"); }; websocket.onmessage = function(event) { $("#js").append("Message Received <br/>"); $("#messages").append(event.data+"<br/>"); }; websocket.onclose = function() { $("#js").append("Connection Closed <br/>"); }; websocket.onerror = function() { $("#js").append("An Error has occurred <br/>"); }; </script> <h3>Chat with Server:</h3> <div id="messages"></div> <input type="text" id="wsmessage"/> <input type="button" value="send" id="wsbutton"/> </body> </html>/demo2 back-end
import java.io.IOException; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/demo2") public class WebSocketDemo2 { @OnOpen public void greeting(Session session) { try { session.getBasicRemote().sendText("Hello from the server!"); session.getBasicRemote().sendText("What's your name?"); } catch (IOException e) { e.printStackTrace(); } } @OnMessage public void message(String message, Session session) { System.out.println(message); try { session.getBasicRemote().sendText("Hello "+ message + ", let's play a game!"); } catch (IOException e) { e.printStackTrace(); } } }
Multi-way chatroom
demo3.html
<html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Demo3 WebSocket</title> <script> $(document).ready( function() { websocket = null; $("#wsbtn").click( function() { var wsUri = "ws://localhost:8080/WebSockets/demo3/" + $("#wsname").val(); websocket = new WebSocket(wsUri); websocket.onopen = function() { $("#js").append("Connection Established<br/>"); }; websocket.onmessage = function(event) { $("#js").append("Message Received <br/>"); $("#messages").append(event.data + "<br/>"); }; websocket.onclose = function() { $("#js").append("Connection Closed <br/>"); }; websocket.onerror = function() { $("#js").append("An Error has occurred <br/>"); }; }); $("#wsbutton").click(function() { websocket.send($("#wsmessage").val()); }); }); </script> </head> <body> Name:<input type="text" id="wsname" /> <input type="button" value="chat!" id="wsbtn" /> <h3>Chat with others:</h3> <div id="messages"></div> <input type="text" id="wsmessage" /> <input type="button" value="send" id="wsbutton" /> </body> </html>demo3 endpoint
import java.io.IOException; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/demo3/{client-id}") public class WebSocketDemo3 { @OnOpen public void greeting(Session session, @PathParam("client-id") String clientId) { try { session.getBasicRemote().sendText( "Hello " + clientId + " welcome to the party!"); for (Session s : session.getOpenSessions()) { s.getBasicRemote().sendText(clientId + " Joined the chat room"); } } catch (IOException e) { e.printStackTrace(); } } @OnMessage public void message(String message, Session session, @PathParam("client-id") String clientId) { try { for (Session s : session.getOpenSessions()) { s.getBasicRemote().sendText(clientId + " says:" + message); } } catch (IOException e) { e.printStackTrace(); } } @OnClose public void close(Session session, @PathParam("client-id") String clientId) { try { for (Session s : session.getOpenSessions()) { s.getBasicRemote().sendText(clientId + " Left the chat room"); } } catch (IOException e) { e.printStackTrace(); } } }