Advertisement
MagnusArias

PS2 | WebSocket 1

Apr 10th, 2017
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.51 KB | None | 0 0
  1. import java.io.IOException;
  2.  
  3. import javax.websocket.OnClose;
  4. import javax.websocket.OnMessage;
  5. import javax.websocket.OnOpen;
  6. import javax.websocket.Session;
  7. import javax.websocket.server.ServerEndpoint;
  8.  
  9. /**
  10.  * @ServerEndpoint gives the relative name for the end point
  11.  * This will be accessed via ws://localhost:8080/EchoChamber/echo
  12.  * Where "localhost" is the address of the host,
  13.  * "EchoChamber" is the name of the package
  14.  * and "echo" is the address to access this class from the server
  15.  */
  16. @ServerEndpoint("/echo")
  17. public class EchoServer {
  18.     /**
  19.      * @OnOpen allows us to intercept the creation of a new session.
  20.      * The session class allows us to send data to the user.
  21.      * In the method onOpen, we'll let the user know that the handshake was
  22.      * successful.
  23.      */
  24.     @OnOpen
  25.     public void onOpen(Session session){
  26.         System.out.println(session.getId() + " has opened a connection");
  27.         try {
  28.             session.getBasicRemote().sendText("Connection Established");
  29.         } catch (IOException ex) {
  30.             ex.printStackTrace();
  31.         }
  32.     }
  33.  
  34.     /**
  35.      * When a user sends a message to the server, this method will intercept the message
  36.      * and allow us to react to it. For now the message is read as a String.
  37.      */
  38.     @OnMessage
  39.     public void onMessage(String message, Session session){
  40.         System.out.println("Message from " + session.getId() + ": " + message);
  41.         try {
  42.             session.getBasicRemote().sendText(message);
  43.         } catch (IOException ex) {
  44.             ex.printStackTrace();
  45.         }
  46.     }
  47.  
  48.     /**
  49.      * The user closes the connection.
  50.      *
  51.      * Note: you can't send messages to the client from this method
  52.      */
  53.     @OnClose
  54.     public void onClose(Session session){
  55.         System.out.println("Session " +session.getId()+" has ended");
  56.     }
  57. }
  58.  
  59.  
  60.  
  61.  
  62. <!DOCTYPE html>
  63.  
  64. <html>
  65.     <head>
  66.         <title>Echo Chamber</title>
  67.         <meta charset="UTF-8">
  68.         <meta name="viewport" content="width=device-width">
  69.     </head>
  70.     <body>
  71.        
  72.         <div>
  73.             <input type="text" id="messageinput"/>
  74.         </div>
  75.         <div>
  76.             <button type="button" onclick="openSocket();" >Open</button>
  77.             <button type="button" onclick="send();" >Send</button>
  78.             <button type="button" onclick="closeSocket();" >Close</button>
  79.         </div>
  80.         <!-- Server responses get written here -->
  81.         <div id="messages"></div>
  82.        
  83.         <!-- Script to utilise the WebSocket -->
  84.         <script type="text/javascript">
  85.                        
  86.             var webSocket;
  87.             var messages = document.getElementById("messages");
  88.            
  89.            
  90.             function openSocket(){
  91.                 // Ensures only one connection is open at a time
  92.                 if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED){
  93.                    writeResponse("WebSocket is already opened.");
  94.                     return;
  95.                 }
  96.                 // Create a new instance of the websocket
  97.                 webSocket = new WebSocket("ws://localhost:8080/EchoChamber/echo");
  98.                  
  99.                 /**
  100.                  * Binds functions to the listeners for the websocket.
  101.                  */
  102.                 webSocket.onopen = function(event){
  103.                     // For reasons I can't determine, onopen gets called twice
  104.                     // and the first time event.data is undefined.
  105.                     // Leave a comment if you know the answer.
  106.                     if(event.data === undefined)
  107.                         return;
  108.  
  109.                     writeResponse(event.data);
  110.                 };
  111.  
  112.                 webSocket.onmessage = function(event){
  113.                     writeResponse(event.data);
  114.                 };
  115.  
  116.                 webSocket.onclose = function(event){
  117.                     writeResponse("Connection closed");
  118.                 };
  119.             }
  120.            
  121.             /**
  122.              * Sends the value of the text input to the server
  123.              */
  124.             function send(){
  125.                 var text = document.getElementById("messageinput").value;
  126.                 webSocket.send(text);
  127.             }
  128.            
  129.             function closeSocket(){
  130.                 webSocket.close();
  131.             }
  132.  
  133.             function writeResponse(text){
  134.                 messages.innerHTML += "<br/>" + text;
  135.             }
  136.            
  137.         </script>
  138.        
  139.     </body>
  140. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement