Example usage for javax.websocket Session getBasicRemote

List of usage examples for javax.websocket Session getBasicRemote

Introduction

In this page you can find the example usage for javax.websocket Session getBasicRemote.

Prototype

RemoteEndpoint.Basic getBasicRemote();

Source Link

Usage

From source file:org.damcode.web.c4webserver.Server.java

private void processMessage(MessageBean m, Session s) throws IOException {
    Player p, o;//  ww w  .j av  a  2s  . c om
    GameController g;

    switch (m.getCommand()) {

    case MessageBean.MSG_CHAT:
        doChatMessage(m, s);
        break;

    case MessageBean.MSG_PASS_MOVE_TOKEN:
        getGame(s).passMoveToken(s);
        break;

    case MessageBean.MSG_MOVE_ACTION:
        int c = Integer.parseInt(m.getData());
        getGame(s).dropPiece(s, c);
        printSysOut("player move: " + m.getData());
        break;

    case MessageBean.MSG_START_GAME:
        if (isAlreadyPlaying(s)) {
            break;
        }
        GameController game = new GameController();
        game.addPlayer(s);
        s.getUserProperties().put("gameid", game.getId());
        waitingGames.add(game);
        game.gameStatus = GameController.GAME_WAITING;

        s.getBasicRemote().sendText(Utils.assembleChatMessage("Server",
                "ok, started game, waiting for players to join.", "server"));

        game.getPlayer(s).sendDataMessage(MessageBean.MSG_START_GAME, game.getId().toString());
        //sendDataMessage(s, , );
        printSysOut("start game: " + m.getData());
        break;

    case MessageBean.MSG_PLAYER_NAME:
        String name = m.getData();
        s.getUserProperties().put("name", name);
        printSysOut("user with name: " + name);
        for (Session ss : s.getOpenSessions()) {
            if (ss.equals(s))
                continue;
            ss.getBasicRemote()
                    .sendText(Utils.assembleChatMessage("Server", "Player join lobby: " + name, "server"));
        }
        break;

    case MessageBean.MSG_JOIN_GAME:
        if (isAlreadyPlaying(s)) {
            break;
        }

        printSysOut("joingame: " + m.getData());
        g = joinGame(s, m);
        if (g != null) {
            try {
                waitingGames.remove(g);
            } catch (Exception e) {
                printSysOut("JOIN FAILED");
            }
        } else {
            printSysOut("NO GAME MATCH FOUND: " + m.getData());
            Utils.sendDataMessage(MessageBean.MSG_PLAYER_QUIT, "Game has expired!", s);
        }
        break;

    case MessageBean.MSG_JOIN_LOBBY_CHAT:
        s.getUserProperties().put("lobby", Boolean.parseBoolean(m.getData()));
        break;

    case MessageBean.MSG_GAME_AVAILABLE:
        if (isAlreadyPlaying(s)) {
            break;
        }
        synchronized (waitingGames) {
            if (waitingGames.isEmpty()) {
                s.getBasicRemote().sendText(
                        Utils.assembleChatMessage("Server", "No games available, try starting one!", "server"));
            }
            for (GameController gc : waitingGames) {
                sendGameAvailMessage(s, gc.getId().toString(), gc.players.get(0));
            }
        }
        break;

    case MessageBean.MSG_PLAYER_READY:
        g = getGame(s);
        if (g == null || g.gameStatus == GameController.GAME_STARTED)
            break;
        printSysOut("gamestate = " + g.gameStatus);
        p = g.getPlayer(s);
        o = g.getOpponent(s);

        p.ready = true;

        if (g.readyCheck()) {
            p.sendDataMessage(MessageBean.MSG_PLAYER_READY, "rdy");
            o.sendDataMessage(MessageBean.MSG_PLAYER_READY, "rdy");
            g.start();
        }
        break;

    case MessageBean.MSG_PLAYER_QUIT:
        quitGame(s, MessageBean.MSG_PLAYER_QUIT);
        break;

    case MessageBean.MSG_PLAYER_SELECT:
        g = getGame(s);
        if (g == null)
            break;
        p = g.getPlayer(s);
        p.imageId = Integer.parseInt(m.getData());
        o = g.getOpponent(s);
        if (o != null) {
            printSysOut("SENT DISABLE MESSAGE: " + p.imageId + " to: " + o.session.getId());
            o.sendDataMessage(MessageBean.MSG_PLAYER_SELECT, m.getData());
        }
        break;

    default:
        break;

    }

}

From source file:org.damcode.web.c4webserver.Server.java

private synchronized void doChatMessage(MessageBean message, Session session) {
    String name = (String) session.getUserProperties().get("name");
    if (name == null) {
        name = "unknown";
    }//  www .  j  ava 2s  . c  o  m

    String data = message.getData().replace("\\", "");
    data = data.replace("\"", "\\\"");

    for (Session s : session.getOpenSessions()) {
        try {
            if (s == session)
                continue;

            if (s.getUserProperties().get("gameid").equals(session.getUserProperties().get("gameid"))) { // only send messages to people in same "game"
                s.getBasicRemote().sendText(Utils.assembleChatMessage(name, data));

            } else if ((Boolean) s.getUserProperties().get("lobby") == true
                    && (Boolean) session.getUserProperties().get("lobby") == true) {
                if (!session.getUserProperties().get("gameid").equals("lobby")) {
                    s.getBasicRemote().sendText(Utils.assembleChatMessage(name, data, "playing"));
                } else {
                    s.getBasicRemote().sendText(Utils.assembleChatMessage(name, data, "lobby"));
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.damcode.web.c4webserver.Server.java

private boolean isAlreadyPlaying(Session s) throws IOException {
    GameController g = getGame(s);/* www  .  j a  va 2s .com*/
    if (g != null) {
        if (g.gameStatus == GameController.GAME_ACTIVE) {
            s.getBasicRemote()
                    .sendText(Utils.assembleChatMessage("Server", "Error, already playing game", "server"));
            return true;
        } else if (g.gameStatus == GameController.GAME_WAITING) {
            s.getBasicRemote()
                    .sendText(Utils.assembleChatMessage("Server", "Error, already waiting for game", "server"));
            return true;

            //            } else if (g.gameStatus == GameController.GAME_STARTED) {
            //
        } else if (g.gameStatus == GameController.GAME_ENDED) {
            s.getBasicRemote()
                    .sendText(Utils.assembleChatMessage("Server", "Please quit current match first", "server"));
            return true;

        }
    }

    return false;
}

From source file:org.damcode.web.c4webserver.Utils.java

public static void sendDataMessage(int cmd, String data, Session session) {
    try {/*w  w  w.  java  2 s .  com*/
        String msg = new JSONObject().put("cmd", cmd).put("data", data).toString();

        session.getBasicRemote().sendText(msg);

    } catch (IOException ex) {
        Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.dicen.recolnat.services.core.MessageProcessorThread.java

private void sendMessage(String message, Session session) {
    // If not synchronized sometimes frames can get randomly lost. No idea why. Behavior appears in Tomcat war but not in stand-alone jar.
    // Randomness is more frequent if not synchronized.
    // Randomness seems to come from using Async, so let's stick with Basic for now.
    if (log.isDebugEnabled()) {
        log.debug("Sending message " + message + " to session " + session.getId());
    }// ww w  .ja  v a  2s. co  m
    synchronized (session) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException ex) {
            log.error("Could not send message to client", ex);
        }
    }
}

From source file:org.erstudio.guper.service.MessageService.java

public void sendMessage(Message message, Session session)
        throws MessageException, IOException, EncodeException {
    checkMessage(message);//from  ww w . jav a  2s  .  co m

    message.setDateTime(new DateTime());
    messageDao.save(message);

    Set<Session> peers = userService.getPeers();
    for (Session peer : peers) {
        peer.getBasicRemote().sendObject(message);
    }
}

From source file:org.sample.whiteboardapp.MyWhiteboard.java

@OnMessage
public void broadcastFigure(Figure figure, Session session) throws IOException, EncodeException {
    System.out.println("broadcastFigure: " + figure);
    JSONObject coordinates = new JSONObject();
    JSONArray lat_json = new JSONArray();
    JSONArray long_json = new JSONArray();
    try {/*  w ww  . java  2  s . co m*/
        /*   FileInputStream in = new FileInputStream("C:\\Users\\Nirmit Shah\\Desktop\\mapsapp_ec504\\location.txt");
           BufferedReader br = new BufferedReader(new InputStreamReader(in));*/
        //sample values
        try {
            double latitude = figure.getJson().getJsonObject("coords").getJsonNumber("Latitude").doubleValue();
            double longitude = figure.getJson().getJsonObject("coords").getJsonNumber("Longitude")
                    .doubleValue();
            double[] coord = { latitude, longitude };
            coordinates = findKNN(coord, root, 1000);
        } catch (NullPointerException e) {
            double max_lat = figure.getJson().getJsonObject("coords").getJsonObject("North_east")
                    .getJsonNumber("lat").doubleValue();
            double max_lng = figure.getJson().getJsonObject("coords").getJsonObject("North_east")
                    .getJsonNumber("lng").doubleValue();
            double min_lat = figure.getJson().getJsonObject("coords").getJsonObject("South_west")
                    .getJsonNumber("lat").doubleValue();
            double min_lng = figure.getJson().getJsonObject("coords").getJsonObject("South_west")
                    .getJsonNumber("lng").doubleValue();
            double[] max = { max_lat, min_lng };
            double[] min = { min_lat, max_lng };
            System.out.println(max_lat + " " + min_lng);
            Vector<Node> v = new Vector();
            rsearch(min, max, root, v);
            for (int i = 0; i < v.size(); i++) {
                Node x = v.get(i);
                // System.out.println(x.point[0] + " "+ x.point[1]);
                lat_json.add(x.point[0]);
                long_json.add(x.point[1]);
            }
            coordinates.put("latitude", lat_json);
            coordinates.put("longitude", long_json);
        }
        /*   String strLine;
           LinkedHashMap<Area, Double> newmap = new LinkedHashMap<Area, Double>();
           while ((strLine = br.readLine()) != null) {
        String[] line = strLine.split("\t");
        double lat = Math.abs(Double.valueOf(line[2])) - latitude;
        double lon = Math.abs(Double.valueOf(line[3])) - longitude;
        double radius = Math.sqrt((Math.pow(lat, 2) + (Math.pow(lon, 2))));
        if (radius != 0) {
            if (!map.isEmpty()) {
                Iterator it = map.entrySet().iterator();
                Boolean found = false;
                newmap.clear();
                while (it.hasNext()) {
                    Map.Entry pair = (Map.Entry) it.next();
                    if ((Double) pair.getValue() >= radius && radius != 0) {
                        found = true;
                        newmap.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
                        if (newmap.size() < 10) {
                            newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                            while (it.hasNext() && newmap.size() < 10) {
                                pair = (Map.Entry) it.next();
                                newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                            }
                        }
                        map = (LinkedHashMap<Area, Double>) newmap.clone();
                        break;
                    } else {
                        newmap.put((Area) pair.getKey(), (Double) pair.getValue());
                    }
                }
                if (!found && map.size() < 10) {
                    map.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
                }
            } else {
                map.put(createArea(line[0], line[1], Double.valueOf(line[2]), Double.valueOf(line[3])), radius);
            }
        }
           }
           in.close();
           Iterator it = map.entrySet().iterator();
           while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        String[] latlong = pair.getKey().toString().split(":") ;
        String lat1 = latlong[1];
        String long1 = latlong[3];
        lat_json.add(lat1);
        long_json.add(long1);                
           }
           coordinates.put("latitude", lat_json);
           coordinates.put("longitude", long_json);*/
        figure.setJson(Json.createReader(new StringReader(coordinates.toString())).readObject());
        RemoteEndpoint.Basic other = session.getBasicRemote();
        other.sendObject(figure);
        System.out.println("sent");
    } catch (Exception e) {
        System.out.println("here");
        e.printStackTrace();
    }

}

From source file:org.springframework.samples.websocket.client.SimpleClientEndpoint.java

@Override
public void onOpen(final Session session, EndpointConfig config) {
    try {/*from ww  w  .  j  a v  a2 s  . c o m*/
        String message = this.greetingService.getGreeting();
        session.getBasicRemote().sendText(message);
    } catch (IOException e) {
        e.printStackTrace();
    }
    session.addMessageHandler(new MessageHandler.Whole<String>() {
        @Override
        public void onMessage(String message) {
            logger.debug("Received message: " + message);
            try {
                session.close();
                logger.debug("Closed session");
            } catch (IOException e) {
                logger.error("Failed to close", e);
            }
        }
    });
}

From source file:org.wso2.appserver.integration.tests.webapp.websocket.EchoWebSocketTestCase.java

@Test(groups = "wso2.as", description = "Testing websocket")
public void testInvokeEchoSample() {
    String echoProgrammaticEndpoint = baseWsUrl + "/example/websocket/echoProgrammatic";
    ;//  ww  w .j  a v  a  2 s  .  c  o  m

    try {
        messageLatch = new CountDownLatch(1);

        final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();

        ClientManager client = ClientManager.createClient();
        Session session = client.connectToServer(new clientEndpoint(), cec, new URI(echoProgrammaticEndpoint));

        session.getBasicRemote().sendText(SENT_MESSAGE);
        messageLatch.await(100, TimeUnit.SECONDS);

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        Assert.fail("Websocket initialization failed due to an exception - " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.identity.agent.outbound.server.messaging.MessageProcessor.java

/**
 * Process User operation in a separate thread
 * @param userOperation User operation message
 *///from   ww  w  .j  ava2  s.c o m
public void processUserOperation(UserOperation userOperation) {

    try {
        Session session = serverHandler.getSession(userOperation.getTenant(), userOperation.getDomain());
        if (session != null) {
            //TODO Check getBasicRemove is thread safe
            session.getBasicRemote().sendText(MessageRequestUtil.getUserOperationJSONMessage(userOperation));
        }
    } catch (IOException ex) {
        LOGGER.error("Error occurred while sending messaging to client. correlationId: "
                + userOperation.getCorrelationId() + " tenant: " + userOperation.getTenant() + " type: "
                + userOperation.getRequestType(), ex);
    }
}