WebSockets
Handshake & endpoints GET /path/to/websocket/endpoint HTTP/1.1 Host: localhost Upgrade: websocket ConnecAon: Upgrade Sec- WebSocket- Key: xqbt3imnzjbyqrinxeflkg== Origin: hsp://localhost Sec- WebSocket- Version: 13 HTTP/1.1 101 Switching Protocols Upgrade: websocket ConnecAon: Upgrade Sec- WebSocket- Accept: K7DJLdLooIwIG/MOpvWFB3y3FE8= ws://host:port/path?query wss://host:port/path?query
CreaAng an endpoint in java Create an endpoint class. Implement the lifecycle methods of the endpoint. Add your business logic to the endpoint. Deploy the endpoint inside a web applicaaon. Note: As opposed to servlets, WebSocket endpoints are instanaated mulaple Ames. The container creates an instance of an endpoint per connecaon to its deployment URI. Each instance is associated with one and only one connecaon. This facilitates keeping user state for each connecaon and makes development easier since there is only one thread execuang the code of an endpoint instance at any given Ame.
ProgrammaAc endpoint public class EchoEndpoint extends Endpoint { @Override public void onopen(final Session session, EndpointConfig config) { session.addmessagehandler(new MessageHandler.Whole<String>() { @Override public void onmessage(string msg) { try { session.getbasicremote().sendtext(msg); catch (IOExcepMon e) {... );
Annotated endpoint @ServerEndpoint("/echo") public class EchoEndpoint { public void onmessage(session session, String msg) { try { session.getbasicremote().sendtext(msg); catch (IOExcepMon e) {...
Lifecycle events ConnecMon opened. @OnOpen public void open(session session, EndpointConfig conf) { Message received. public void message (Session session, String msg) { ConnecMon error. @OnError public void error(session session, Throwable error) { ConnecMon closed. @OnClose public void close(session session, CloseReason reason) {
Receiving messages You can have at most three methods annotated with in an endpoint, one for each message type: text, Binary, pong. @ServerEndpoint("/receive") public class ReceiveEndpoint { public void textmessage(session session, String msg) { System.out.println("Text message: " + msg); public void binarymessage(session session, ByteBuffer msg) { System.out.println("Binary message: " + msg.tostring()); public void pongmessage(session session, PongMessage msg) { System.out.println("Pong message: " + msg.getapplicamondata().tostring());
Sending messages to all connected peers @ServerEndpoint("/echoall") public class EchoAllEndpoint { public void onmessage(session session, String msg) { try { for (Session sess : session.getopensessions()) { if (sess.isopen()) sess.getbasicremote().sendtext(msg); catch (IOExcepMon e) {...
Mantaining the state Remember: the container creates an instance of the endpoint class for every connecaon! The Session.getUserProperAes method provides a modifiable map to store user properaes. @ServerEndpoint("/delayedecho") public class DelayedEchoEndpoint { @OnOpen public void open(session session) { session.getuserpropermes().put("previousmsg", " "); public void message(session session, String msg) { String prev = (String) session.getuserpropermes().get("previousmsg"); session.getuserpropermes().put("previousmsg", msg); try { session.getbasicremote().sendtext(prev); catch (IOExcepMon e) {... To store informaaon common to all connected clients, you can use class (staac) variables; however, you are responsible for ensuring thread- safe access to them.
Parametrising mulaple endpoints hsp://localhost:8080/chatapp/chatrooms/currentnews hsp://localhost:8080/chatapp/chatrooms/music hsp://localhost:8080/chatapp/chatrooms/cars @ServerEndpoint("/chatrooms/{room- name") public class ChatEndpoint { @OnOpen public void open(session session, EndpointConfig c, @PathParam("room- name") String roomname) { // Add the client to the chat room of their choice...
Websocket client side (JS) - head var connecaon = new WebSocket('ws://echo.websocket.org/') // When we open the connecaon, we send a msg to theserver connecaon.onopen = funcaon () { connecaon.send( Hello'); ; // Errors (onconsole) connecaon.onerror = funcaon (error) { console.log('websocket Error ' + error); ; // When genng messages from the server connecaon.onmessage = funcaon (e) { console.log('server: ' + e.data); ;
Websocket client side (JS) - body connecaon.send('contenuto del messaggio');