Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.util.Map;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.inject.Inject;
- import javax.websocket.EncodeException;
- import javax.websocket.OnClose;
- import javax.websocket.OnError;
- import javax.websocket.OnMessage;
- import javax.websocket.OnOpen;
- import javax.websocket.Session;
- import javax.websocket.server.PathParam;
- import javax.websocket.server.ServerEndpoint;
- /**
- * @ServerEndpoint gives the relative name for the end point
- * This will be accessed via ws://localhost:8080/EchoChamber/echo
- * Where "localhost" is the address of the host,
- * "EchoChamber" is the name of the package
- * and "echo" is the address to access this class from the server
- */
- @ServerEndpoint(value = "/echo/{roomnumber}")
- public class EchoServer {
- /**
- * @OnOpen allows us to intercept the creation of a new session.
- * The session class allows us to send data to the user.
- * In the method onOpen, we'll let the user know that the handshake was
- * successful.
- */
- @OnOpen
- public void onOpen(Session session, @PathParam("roomnumber") String roomnumber){
- System.out.println(session.getId() + " has opened a connection");
- session.getUserProperties().put("roomnumber", roomnumber);
- SessionHandler.openSessions.put(String.valueOf(session.getId()), session);
- SessionHandler.addSession(session);
- }
- /**
- * When a user sends a message to the server, this method will intercept the message
- * and allow us to react to it. For now the message is read as a String.
- */
- @OnMessage
- public void onMessage(String message, Session session){
- String room = (String) session.getUserProperties().get("roomnumber");
- try{
- for (Session s : session.getOpenSessions()){
- if (s.isOpen() && s.getUserProperties().get("roomnumber").equals(room)){
- s.getBasicRemote().sendObject(message);
- }
- }
- }
- catch (IOException| EncodeException e){
- }
- }
- /**
- * The user closes the connection.
- *
- * Note: you can't send messages to the client from this method
- */
- @OnClose
- public void onClose(Session session){
- System.out.println("Session " +session.getId()+" has ended");
- SessionHandler.removeSession(session);
- }
- @OnError
- public void onError(Throwable error) {
- Logger.getLogger(EchoServer.class.getName()).log(Level.SEVERE, null, error);
- }
- }
- <!DOCTYPE html>
- <html>
- <head>
- <title>Echo Chamber</title>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width">
- </head>
- <body>
- <div>
- Room ID:<input type="text" id="roomnumber"/>
- </div>
- <div>
- Message :<input type="text" id="messageinput"/>
- </div>
- <div>
- <button type="button" onclick="openSocket();" >Open</button>
- <button type="button" onclick="send();" >Send</button>
- <button type="button" onclick="closeSocket();" >Close</button>
- </div>
- <!-- Server responses get written here -->
- <div id="messages"></div>
- <!-- Script to utilise the WebSocket -->
- <script type="text/javascript">
- var webSocket;
- var messages = document.getElementById("messages");
- function openSocket(){
- // Ensures only one connection is open at a time
- if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED){
- writeResponse("WebSocket is already opened.");
- return;
- }
- // Create a new instance of the websocket
- webSocket = new WebSocket("ws://localhost:8080/EchoChamber/echo/" + document.getElementById("roomnumber").value);
- /**
- * Binds functions to the listeners for the websocket.
- */
- webSocket.onopen = function(event){
- // For reasons I can't determine, onopen gets called twice
- // and the first time event.data is undefined.
- // Leave a comment if you know the answer.
- if(event.data === undefined)
- return;
- writeResponse(event.data);
- };
- webSocket.onmessage = function(event){
- writeResponse(event.data);
- };
- webSocket.onclose = function(event){
- writeResponse("Connection closed");
- };
- }
- /**
- * Sends the value of the text input to the server
- */
- function send(){
- var text = document.getElementById("messageinput").value;
- webSocket.send(text);
- }
- function closeSocket(){
- webSocket.close();
- }
- function writeResponse(text){
- messages.innerHTML += "<br/>" + text;
- }
- </script>
- </body>
- </html>
- \
- import java.io.IOException;
- import java.util.HashSet;
- import java.util.Map;
- import java.util.Set;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.websocket.Session;
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- /**
- *
- * @author student_10
- */
- public class SessionHandler {
- private static final Set<Session> sessions = new HashSet<>();
- static Map<String, Session> openSessions;
- public static void addSession(Session session){
- sessions.add(session);
- }
- public static void removeSession(Session session){
- sessions.remove(session);
- }
- public static void sendToSession(Session session, String message){
- try {
- session.getBasicRemote().sendText(message.toString());
- } catch (IOException ex) {
- sessions.remove(session);
- Logger.getLogger(SessionHandler.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- public static void sendToallConnectedSessions(String message){
- for (Session session : sessions) {
- sendToSession(session, message);
- }
- }
- public static void sendToallConnectedSessionsInRoom(String roomID, String message){
- for (Session session : sessions) {
- sendToSession(session, message);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement