Advertisement
MagnusArias

PS2 | WebSocket 3

Apr 24th, 2017
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.87 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.util.Map;
  3. import java.util.logging.Level;
  4. import java.util.logging.Logger;
  5. import javax.inject.Inject;
  6. import javax.websocket.EncodeException;
  7.  
  8. import javax.websocket.OnClose;
  9. import javax.websocket.OnError;
  10. import javax.websocket.OnMessage;
  11. import javax.websocket.OnOpen;
  12. import javax.websocket.Session;
  13. import javax.websocket.server.PathParam;
  14. import javax.websocket.server.ServerEndpoint;
  15.  
  16. /**
  17.  * @ServerEndpoint gives the relative name for the end point
  18.  * This will be accessed via ws://localhost:8080/EchoChamber/echo
  19.  * Where "localhost" is the address of the host,
  20.  * "EchoChamber" is the name of the package
  21.  * and "echo" is the address to access this class from the server
  22.  */
  23. @ServerEndpoint(value = "/echo/{roomnumber}")
  24. public class EchoServer {
  25.     /**
  26.      * @OnOpen allows us to intercept the creation of a new session.
  27.      * The session class allows us to send data to the user.
  28.      * In the method onOpen, we'll let the user know that the handshake was
  29.      * successful.
  30.      */    
  31.  
  32.    
  33.     @OnOpen
  34.     public void onOpen(Session session, @PathParam("roomnumber") String roomnumber){
  35.         System.out.println(session.getId() + " has opened a connection");
  36.             session.getUserProperties().put("roomnumber", roomnumber);
  37.             SessionHandler.openSessions.put(String.valueOf(session.getId()), session);
  38.             SessionHandler.addSession(session);
  39.     }
  40.  
  41.     /**
  42.      * When a user sends a message to the server, this method will intercept the message
  43.      * and allow us to react to it. For now the message is read as a String.
  44.      */
  45.     @OnMessage
  46.     public void onMessage(String message, Session session){
  47.         String room = (String) session.getUserProperties().get("roomnumber");
  48.         try{
  49.             for (Session s : session.getOpenSessions()){
  50.                 if (s.isOpen() && s.getUserProperties().get("roomnumber").equals(room)){
  51.                     s.getBasicRemote().sendObject(message);
  52.                 }
  53.             }
  54.         }
  55.         catch (IOException| EncodeException e){
  56.            
  57.         }
  58.     }
  59.  
  60.     /**
  61.      * The user closes the connection.
  62.      *
  63.      * Note: you can't send messages to the client from this method
  64.      */
  65.     @OnClose
  66.     public void onClose(Session session){
  67.         System.out.println("Session " +session.getId()+" has ended");
  68.         SessionHandler.removeSession(session);
  69.        
  70.     }
  71.    
  72.     @OnError
  73.     public void onError(Throwable error) {
  74.         Logger.getLogger(EchoServer.class.getName()).log(Level.SEVERE, null, error);
  75.     }
  76. }
  77.  
  78.  
  79.  
  80.  
  81. <!DOCTYPE html>
  82.  
  83. <html>
  84.     <head>
  85.         <title>Echo Chamber</title>
  86.         <meta charset="UTF-8">
  87.         <meta name="viewport" content="width=device-width">
  88.     </head>
  89.     <body>
  90.        
  91.         <div>
  92.             Room ID:<input type="text" id="roomnumber"/>
  93.         </div>
  94.         <div>
  95.             Message :<input type="text" id="messageinput"/>
  96.         </div>
  97.         <div>
  98.             <button type="button" onclick="openSocket();" >Open</button>
  99.             <button type="button" onclick="send();" >Send</button>
  100.             <button type="button" onclick="closeSocket();" >Close</button>
  101.         </div>
  102.         <!-- Server responses get written here -->
  103.         <div id="messages"></div>
  104.        
  105.         <!-- Script to utilise the WebSocket -->
  106.         <script type="text/javascript">
  107.                        
  108.             var webSocket;
  109.             var messages = document.getElementById("messages");
  110.            
  111.            
  112.             function openSocket(){
  113.                 // Ensures only one connection is open at a time
  114.                 if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED){
  115.                    writeResponse("WebSocket is already opened.");
  116.                     return;
  117.                 }
  118.                 // Create a new instance of the websocket
  119.                 webSocket = new WebSocket("ws://localhost:8080/EchoChamber/echo/" + document.getElementById("roomnumber").value);
  120.                  
  121.                 /**
  122.                  * Binds functions to the listeners for the websocket.
  123.                  */
  124.                 webSocket.onopen = function(event){
  125.                     // For reasons I can't determine, onopen gets called twice
  126.                     // and the first time event.data is undefined.
  127.                     // Leave a comment if you know the answer.
  128.                     if(event.data === undefined)
  129.                         return;
  130.  
  131.                     writeResponse(event.data);
  132.                 };
  133.  
  134.                 webSocket.onmessage = function(event){
  135.                     writeResponse(event.data);
  136.                 };
  137.  
  138.                 webSocket.onclose = function(event){
  139.                     writeResponse("Connection closed");
  140.                 };
  141.             }
  142.            
  143.             /**
  144.              * Sends the value of the text input to the server
  145.              */
  146.             function send(){
  147.                 var text = document.getElementById("messageinput").value;
  148.                 webSocket.send(text);
  149.             }
  150.            
  151.             function closeSocket(){
  152.                 webSocket.close();
  153.             }
  154.  
  155.             function writeResponse(text){
  156.                 messages.innerHTML += "<br/>" + text;
  157.             }
  158.            
  159.         </script>
  160.        
  161.     </body>
  162. </html>
  163.  
  164.  
  165.  
  166.  
  167. \
  168. import java.io.IOException;
  169. import java.util.HashSet;
  170. import java.util.Map;
  171. import java.util.Set;
  172. import java.util.logging.Level;
  173. import java.util.logging.Logger;
  174. import javax.websocket.Session;
  175.  
  176. /*
  177.  * To change this license header, choose License Headers in Project Properties.
  178.  * To change this template file, choose Tools | Templates
  179.  * and open the template in the editor.
  180.  */
  181.  
  182. /**
  183.  *
  184.  * @author student_10
  185.  */
  186. public class SessionHandler {
  187.     private static final Set<Session> sessions = new HashSet<>();
  188.     static Map<String, Session> openSessions;
  189.    
  190.     public static void addSession(Session session){
  191.         sessions.add(session);
  192.     }
  193.    
  194.     public static void removeSession(Session session){
  195.         sessions.remove(session);
  196.     }
  197.    
  198.     public static void sendToSession(Session session, String message){
  199.        try {
  200.             session.getBasicRemote().sendText(message.toString());
  201.         } catch (IOException ex) {
  202.             sessions.remove(session);
  203.             Logger.getLogger(SessionHandler.class.getName()).log(Level.SEVERE, null, ex);
  204.         }
  205.     }
  206.    
  207.     public static void sendToallConnectedSessions(String message){
  208.          for (Session session : sessions) {
  209.             sendToSession(session, message);
  210.         }
  211.     }
  212.    
  213.     public static void sendToallConnectedSessionsInRoom(String roomID, String message){
  214.          for (Session session : sessions) {
  215.             sendToSession(session, message);
  216.         }
  217.     }
  218. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement