09. Using WebSockets and HTTP
Introduction
Thanks to BalusC for the valuable information!
WebSockets enables server-client communication much more fluently than servlets! In long processes, you can inform the user of everything that is happening in time. In the servlets, you need to wait till the process has ended or use asynchronous servlets that are prune error.
Information on WebServlets can be seen on Oracle web. and better in another post from Abhishek Gupta
Here is his code but changing "javax" with "jakarta"
These files are needed:
- A java WebSocket endpoint (EndPoint.java)
- A Server Endpoint Config.Configurator (HttpSessionConfigurator.java)
- A client WebSocket implemented in Html with javascript code (websocket.html)
EndPoint.java
package gupta; import java.io.IOException; //import http.SessionWrapper; import jakarta.servlet.http.HttpSession; import jakarta.websocket.EndpointConfig; import jakarta.websocket.OnOpen; import jakarta.websocket.Session; import jakarta.websocket.server.PathParam; import jakarta.websocket.server.ServerEndpoint; import openadmin.model.control.MenuItem; @ServerEndpoint(value = "/gupta/{user}", configurator = HttpSessionConfigurator.class) public class Service { private EndpointConfig config; @OnOpen public void opened(@PathParam("user") String user, Session session, EndpointConfig config) throws IOException { this.config = config; } @OnMessage public void onReceipt(Session session,String message) throws IOException { System.out.println("==============================================================================="); System.out.println("Got message:"+message); System.out.println("==============================================================================="); session.getBasicRemote().sendText("echo 1"+message); session.getBasicRemote().sendText("echo 2"+message); session.getBasicRemote().sendText("echo 3"+message); //Close the connection form server CloseReason closeReason= new CloseReason(CloseCodes.NORMAL_CLOSURE, "It's time to close!...."); session.close(closeReason); @OnMessage public void binaryMessage(Session session, ByteBuffer msg) { System.out.println("I am sending this Binary message: " + msg.toString()); } @OnMessage public void pongMessage(Session session, PongMessage msg) { System.out.println("Pong message: " + msg.getApplicationData().toString()); } @OnClose public void handleClose() { System.out.println("Desconnected client .......!"); } @OnError public void handleError(Throwable t) { t.printStackTrace(); } }
HttpSessionConfigurator.java
NOTE: It is important to verify that the httpSession is not null, or else when storing it in the map, an exception is thrown!!!
package gupta; import jakarta.servlet.http.HttpSession; import jakarta.websocket.HandshakeResponse; import jakarta.websocket.server.HandshakeRequest; import jakarta.websocket.server.ServerEndpointConfig; public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator { @Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { //System.out.println("modifyHandshake() Current thread " + Thread.currentThread().getName()); HttpSession httpSession = (HttpSession) request.getHttpSession(); Map<String, Object> mp =config.getUserProperties(); if (mp==null ) System.out.println("config.getUserProperties() is null"); else if (httpSession==null) System.out.println("httpSession is null"); else mp.put("httpSession", httpSession); } }
websocket.html
<!DOCTYPE html> <html> <head> <!-- jQuery --> <script src="http://code.jquery.com/jquery-latest.js"> </script> <meta charset="UTF-8"> <title>websocket tutorial</title> </head> <body> <form> <input id="textMessage" type="text"> <input onclick="sendMessage();" value="Send Message" type="button"> </form> <br> <textarea id="messagesTextArea" rows="10" cols="50"></textarea> <script type="text/javascript"> var webSocket =new WebSocket("ws://localhost:8080/JSP-05/gupta/ximo"); // ws://<host>:<port>/application>/<path>/<path param> var messagesTextArea = document.getElementById("messagesTextArea"); webSocket.onopen = function (message) { processOpen(message);}; webSocket.onclose = function (message) { processClose(message);}; webSocket.onerror = function (message) { processError(message);}; webSocket.onmessage = function (message) { processMessage(message);}; function processOpen(message) { messagesTextArea.value += "Server Connect...."+"\n"; } function processMessage(message) { messagesTextArea.value += "Receive From Server ==>" + message.data + "\n"; function sendMessage(message) { if (textMessage.value!="close") { webSocket.send(textMessage.value); messagesTextArea.value += "Sent to server.===>"+ textMessage.value + "\n"; textMessage.value=""; }else websocket.close(); } function processClose(message) { webSocket.send("client disconnected...."); messagesTextArea.value += "Server Disconnect...."+"\n"; } function processError(message) { messagesTextArea.value += "error...."+"\n"; } </script> </body> </html>
Comentarios
Publicar un comentario