Java 类play.mvc.WebSocket 实例源码

项目:galaxy    文件:RaceChatModel.java   
private void sendHistoryMessage(WebSocket.Out<JsonNode> channel, History history) {
    if (m_members.values().size() > SIZE_THRESHOLD) {
        return;
    }

    ObjectNode event = Json.newObject();
    event.put("kind", "history");
    event.put("user", history.talk.username);
    event.put("message", history.talk.text);
    event.put("userId", history.talk.userId);
    event.put("toUser", history.talk.toUserName);
    event.put("toUserId", history.talk.toUserId);
    event.put("isOnline", history.talk.isOnline);
    event.put("isOwners", history.talk.isOwners);
    event.put("peopleNum", m_members.keySet().size());
    event.put("time", sdf.format(history.date));

    channel.write(event);
}
项目:cros-core    文件:DroneController.java   
public static WebSocket<String> videoSocket(long id) {
    String[] tokens = request().queryString().get("authToken");

    if (tokens == null || tokens.length != 1 || tokens[0] == null)
        return WebSocket.reject(unauthorized());

    Drone drone = Drone.FIND.byId(id);
    if (drone == null)
        return WebSocket.reject(notFound(Json.toJson("no drone found with this id")));

    User u = models.User.findByAuthToken(tokens[0]);
    if (u != null) {
        return WebSocket.withActor(out -> VideoWebSocket.props(out, id));
    } else {
        return WebSocket.reject(unauthorized());
    }
}
项目:cros-core    文件:Application.java   
public static WebSocket<String> videoSocket(long id) {
    /*String[] tokens = request().queryString().get("authToken");

    if (tokens == null || tokens.length != 1 || tokens[0] == null)
        return WebSocket.reject(unauthorized());

    User u = models.User.findByAuthToken(tokens[0]);
    if (u != null) {
        return WebSocket.withActor(out -> VideoWebSocket.props(out, id));
    } else {
        return WebSocket.reject(unauthorized());
    }*/
    Drone drone = Drone.FIND.byId(id);
    DroneCommander d = Fleet.getFleet().getCommanderForDrone(drone);
    d.initVideo();

    return WebSocket.withActor(out -> VideoWebSocket.props(out, id));
}
项目:PlayTraining    文件:Server.java   
private Server(ActorRef messageRoom) {

        // Create a Fake socket out for the robot that log events to the console.
        WebSocket.Out<JsonNode> serverChannel = new WebSocket.Out<JsonNode>() {

            public void write(JsonNode frame) {
                Logger.info(Json.stringify(frame));
            }

            public void close() {
            }
        };

        // Join the room
        messageRoom.tell(new MessageRoom.Join("Server", serverChannel), null);
    }
项目:PlayTraining    文件:Socket.java   
/**
 * Action non standard dédiée aux WebSockets
 */
public static WebSocket<JsonNode> connect() {
    // On peut récupérer des objets de session ici si besoin!
    return new WebSocket<JsonNode>() {
        // Appelé quand le "Handshake" est réalisé lors de la première requête HTTP.
        public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {

            // Joindre la pièce dédiée aux messages.
            try {
                MessageRoom.join(UUID.randomUUID().toString(), in, out);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
}
项目:PlayTraining    文件:Server.java   
private Server(ActorRef messageRoom) {

        // Create a Fake socket out for the robot that log events to the console.
        WebSocket.Out<JsonNode> serverChannel = new WebSocket.Out<JsonNode>() {

            public void write(JsonNode frame) {
                Logger.info(Json.stringify(frame));
            }

            public void close() {
            }
        };

        // Join the room
        messageRoom.tell(new MessageRoom.Join("Server", serverChannel), null);
    }
项目:PlayTraining    文件:Socket.java   
/**
 * Action non standard dédiée aux WebSockets
 */
public static WebSocket<JsonNode> connect() {
    // On peut récupérer des objets de session ici si besoin!
    return new WebSocket<JsonNode>() {
        // Appelé quand le "Handshake" est réalisé lors de la première requête HTTP.
        public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {

            // Joindre la pièce dédiée aux messages.
            try {
                MessageRoom.join(UUID.randomUUID().toString(), in, out);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
}
项目:PlayTraining    文件:Server.java   
private Server(ActorRef messageRoom) {

        // Create a Fake socket out for the robot that log events to the console.
        WebSocket.Out<JsonNode> serverChannel = new WebSocket.Out<JsonNode>() {

            public void write(JsonNode frame) {
                Logger.info(Json.stringify(frame));
            }

            public void close() {
            }
        };

        // Join the room
        messageRoom.tell(new MessageRoom.Join("Server", serverChannel), null);
    }
项目:PlayTraining    文件:Socket.java   
/**
 * Action non standard dédiée aux WebSockets
 */
public static WebSocket<JsonNode> connect() {
    // On peut récupérer des objets de session ici si besoin!
    return new WebSocket<JsonNode>() {
        // Appelé quand le "Handshake" est réalisé lors de la première requête HTTP.
        public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {

            // Joindre la pièce dédiée aux messages.
            try {
                MessageRoom.join(UUID.randomUUID().toString(), in, out);
            } catch (Exception ex) {
                Logger.error("Error in WebSocket onReady", ex);
            }
        }
    };
}
项目:PlayTraining    文件:Server.java   
private Server(ActorRef messageRoom) {

        // Create a Fake socket out for the robot that log events to the console.
        WebSocket.Out<JsonNode> serverChannel = new WebSocket.Out<JsonNode>() {

            public void write(JsonNode frame) {
                Logger.info(Json.stringify(frame));
            }

            public void close() {
            }
        };

        // Join the room
        messageRoom.tell(new MessageRoom.Join("Server", serverChannel), null);
    }
项目:PlayTraining    文件:Socket.java   
/**
 * Action non standard dédiée aux WebSockets
 */
public static WebSocket<JsonNode> connect() {
    // On peut récupérer des objets de session ici si besoin!
    return new WebSocket<JsonNode>() {
        // Appelé quand le "Handshake" est réalisé lors de la première requête HTTP.
        public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {

            // Joindre la pièce dédiée aux messages.
            try {
                MessageRoom.join(UUID.randomUUID().toString(), in, out);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
}
项目:htwplus    文件:WebSocketService.java   
/**
 * Invokes a new ActorRef instance of type WebSocketActor for an account ID.
 *
 * @param account Account
 * @param in WebSocket input stream
 * @param out WebSocket output stream
 */
public void invokeActor(final Account account, WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
    if (this.getActorForAccount(account) != null) {
        return;
    }

    this.accountActor.put(account.id, Akka.system().actorOf(Props.create(WebSocketActor.class, account, in, out)));
}
项目:Hermodr-Server    文件:Session.java   
private void sendCompleteImage(WebSocket.Out<JsonNode> viewer) {

    for (int x = 0; x < imageStrings.length; x++) {
        for (int y = 0; y < imageStrings[x].length; y++) {
            if (imageStrings[x][y] != null) {
                ObjectNode event = Json.newObject();
                event.put("kind", "sendImage");
                event.put("x", x);
                event.put("y", y);
                event.put("data", imageStrings[x][y]);
                viewer.write(event);
            }
        }
    }

}
项目:Hermodr-Server    文件:Application.java   
public static WebSocket<JsonNode> presenter(final String presenterName) {
    Logger.info("Application.presenter()");
    return new WebSocket<JsonNode>() {

        // Called when the Websocket Handshake is done.
        public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){

            // Join the chat room.
            try { 
                Session.createSession(presenterName, in, out);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
}
项目:Hermodr-Server    文件:Application.java   
public static WebSocket<JsonNode> viewer(final String presenterName, final String username) {
    Logger.info("Application.viewer()");
    return new WebSocket<JsonNode>() {

        // Called when the Websocket Handshake is done.
        public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){

            // Join the chat room.
            try { 
                Session.joinSession(presenterName, username, in, out);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
}
项目:NationStatesPlusPlus    文件:WebsocketManager.java   
protected void register(NationStatesWebSocket socket, WebSocket.In<JsonNode> in) {
    Set<NationStatesWebSocket> set = pages.get(socket.getPageType());
    synchronized(set) {
        set.add(socket);
        in.onClose(new UnregisterCallback(socket));
    }

    count++;
    if (count % 25 == 0) {
        int total = 0;
        for (PageType page : PageType.values()) {
            Set<NationStatesWebSocket> sockets = pages.get(page);
            synchronized(sockets) {
                total += sockets.size();
            }
        }
        Logger.info("Currently " + total + " registered websockets");
    }
}
项目:play-workshop    文件:FitnessController.java   
public static WebSocket<String> wsCall() {
    return new WebSocket<String>() {
        @SuppressWarnings("unchecked")
        public void onReady(final WebSocket.In<String> in,
                            final WebSocket.Out<String> out) {

            if (Cache.get("channels") == null) {
                List<Out> outs = new ArrayList<Out>();
                outs.add(out);
                Cache.set("channels", outs);
            } else ((List<Out>) Cache.get("channels")).add(out);
            System.out.println("<" + Cache.get("channels"));
            in.onClose(new F.Callback0() {
                @Override
                public void invoke() throws Throwable {
                    ((List<Out>) Cache.get("channels")).remove(out);
                    out.close();
                }
            });
        }
    };
}
项目:play2-prototypen    文件:SinglePlayerGameHall.java   
private static void initializeGame(ActionRequest actionRequest) {

        final Game game = findGame((Long) actionRequest.data[0]);
        // change game state
        game.superState = Game.STATE_READY;
        game.subState = 0;
        // set active counter to first position in the list of counters
        game.activeCounter = 0;

        // construct the action response
        ActionResponse response = new ActionResponse();
        // define socket request initializing action
        response.initializer = Action.TYPE_INITIALIZE_GAME;
        // assemble socket response data
        response = assembleInitializeGameResponseData(game, response);

        @SuppressWarnings("unchecked")
        WebSocket.Out<JsonNode> out = (WebSocket.Out<JsonNode>) actionRequest.data[1];

        // finally write action response on the socket's out channel
        writeOut(response, out);

        // persist the game state
        game.save();
    }
项目:play2-prototypen    文件:GameController.java   
/**
 * Controller Action for initiating the web socket.
 */
public static WebSocket<JsonNode> initializeSinglePlayerGame(final Long game) {

    final Session session = session();

    return new WebSocket<JsonNode>() {

        public void onReady(WebSocket.In<JsonNode> in,
                WebSocket.Out<JsonNode> out) {
            try {
                SinglePlayerGameHall.join(game,
                        UserService.getAuthUserName(session), in, out);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
}
项目:play2-prototypen    文件:Playgrounds.java   
/**
 * Websocket für das Administrieren der Spielfelder verwalten.
 */
public static WebSocket<JsonNode> administratePlayground() {

    final User user = getUMS().getLoggedUser(session());

    return new WebSocket<JsonNode>() {

           public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){                
               try { 
                   GameHall.join(user, in, out);
               } catch (Exception ex) {
                   ex.printStackTrace();
               }
           }
       };       
}
项目:galaxy    文件:RaceChatModel.java   
public RaceChatModel(String hostId, Map<String, WebSocket.Out<JsonNode>> members) {
    m_hostId = hostId;
    m_members = members;
    recordList = new ArrayList<History>();
    drawedDict = new HashMap<String, Integer>();
    flowerWinnerList = new ArrayList<String>();
}
项目:galaxy    文件:RaceChatModel.java   
private void notifyAll(String kind, String user,String userId,String toUserName,String toUserId, String text,boolean isOnline,boolean isOwners) {

        /*
        if (m_members.values().size() > SIZE_THRESHOLD) {
            if (kind.compareToIgnoreCase("talk") != 0 &&
                kind.compareToIgnoreCase("present") != 0) {
                if (userId == null || m_roomId == null) {
                    return;
                }

                if (userId.compareToIgnoreCase(m_roomId) != 0) {
                    return;
                }

                //ban zhulaile
                Logger.info(kind + ":" + userId + " " + user);
            }
        }
        */

        for(WebSocket.Out<JsonNode> channel: m_members.values()) {
            ObjectNode event = Json.newObject();
            event.put("kind", kind);
            event.put("user", user);
            event.put("message", text);
            event.put("userId", userId);
            event.put("toUser", toUserName);
            event.put("toUserId", toUserId);
            event.put("isOnline", isOnline);
            event.put("isOwners", isOwners);
            event.put("peopleNum", m_members.keySet().size());

            try {
                channel.write(event);                
            }
            catch (Throwable e) {
            }
        }
    }
项目:galaxy    文件:ChatRoom.java   
public Join(String username,String userId, WebSocket.Out<JsonNode> channel,boolean isOnline,boolean isOwners) {
    this.username = username;
    this.userId = userId;
    this.channel = channel;
    this.isOnline =isOnline ;
    this.isOwners = isOwners;
}
项目:Simple-Chat-Websocket-Java-PlayFramework    文件:Application.java   
public static WebSocket<String> wsInterface() {
    return new WebSocket<String>() {
        @Override
        public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
            SimpleChat.start(in,out);
        }
    };
}
项目:twitter-analyst    文件:Application.java   
/**
 * Starts a new websocket connection per request.
 * It uses an akka actor instance to communicate with
 * client.
 *
 * @return WebSocket
 */
public static WebSocket<String> wsTweets() {
    return WebSocket.withActor(new F.Function<ActorRef, Props>() {
        public Props apply(ActorRef out) throws Throwable {
            return TweetPublisher.props(out);
        }
    });
}
项目:cros-core    文件:Application.java   
public static WebSocket<String> testSocket() {
    String[] tokens = request().queryString().get("authToken");

    if (tokens == null || tokens.length != 1 || tokens[0] == null)
        return WebSocket.reject(unauthorized());

    User u = models.User.findByAuthToken(tokens[0]);
    if (u != null) {
        return WebSocket.withActor(NotificationSimulator::props);
    } else {
        return WebSocket.reject(unauthorized());
    }
}
项目:cros-core    文件:Application.java   
public static WebSocket<String> socket() {
    String[] tokens = request().queryString().get("authToken");

    if (tokens == null || tokens.length != 1 || tokens[0] == null)
        return WebSocket.reject(unauthorized());

    User u = models.User.findByAuthToken(tokens[0]);
    if (u != null) {
        return WebSocket.withActor(MessageWebSocket::props);
    } else {
        return WebSocket.reject(unauthorized());
    }
}
项目:wbi    文件:BaseWebSocketController.java   
/**
 * Start WebSocket session.
 *
 * @return {@code WebSocket}.
 */
public static WebSocket<String> socket() {
    return WebSocket.withActor(new F.Function<ActorRef, Props>() {
        @Override
        public Props apply(ActorRef out) throws Throwable {
            return WebSocketActor.props(out);
        }
    });
}
项目:PlayTraining    文件:MessageRoom.java   
/**
 * Join the default room.
 */
public static void join(final String username, WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out)
        throws Exception {

    // Send the Join message to the room
    String result = (String) Await.result(ask(ROOM, new Join(username, out), 1000), Duration.create(1, SECONDS));

    if ("OK".equals(result)) {

        // For each event received on the socket,
        in.onMessage(new Callback<JsonNode>() {
            public void invoke(JsonNode event) {

                // Send a Talk message to the room.
                ROOM.tell(new Talk(username, event.get("text").asText()), null);

            }
        });

        // When the socket is closed.
        in.onClose(new Callback0() {
            public void invoke() {

                // Send a Quit message to the room.
                ROOM.tell(new Quit(username), null);

            }
        });
    } else {
        // Cannot connect, create a Json error.
        ObjectNode error = Json.newObject();
        error.put("error", result);

        // Send the error to the socket.
        out.write(error);
    }
}
项目:PlayTraining    文件:MessageRoom.java   
/**
 * Join the default room.
 */
public static void join(final String username, WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out)
        throws Exception {

    // Send the Join message to the room
    String result = (String) Await.result(ask(ROOM, new Join(username, out), 1000), Duration.create(1, SECONDS));

    if ("OK".equals(result)) {

        // For each event received on the socket,
        in.onMessage(new Callback<JsonNode>() {
            public void invoke(JsonNode event) {

                // Send a Talk message to the room.
                ROOM.tell(new Talk(username, event.get("text").asText()), null);

            }
        });

        // When the socket is closed.
        in.onClose(new Callback0() {
            public void invoke() {

                // Send a Quit message to the room.
                ROOM.tell(new Quit(username), null);

            }
        });
    } else {
        // Cannot connect, create a Json error.
        ObjectNode error = Json.newObject();
        error.put("error", result);

        // Send the error to the socket.
        out.write(error);
    }
}
项目:PlayTraining    文件:MessageRoom.java   
/**
 * Join the default room.
 */
public static void join(final String username, WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out)
        throws Exception {

    // Send the Join message to the room
    String result = (String) Await.result(ask(ROOM, new Join(username, out), 1000), Duration.create(1, SECONDS));

    if ("OK".equals(result)) {

        // For each event received on the socket,
        in.onMessage(new Callback<JsonNode>() {
            public void invoke(JsonNode event) {

                // Send a Talk message to the room.
                ROOM.tell(new Talk(username, event.get("text").asText()), null);

            }
        });

        // When the socket is closed.
        in.onClose(new Callback0() {
            public void invoke() {

                // Send a Quit message to the room.
                ROOM.tell(new Quit(username), null);

            }
        });
    } else {
        // Cannot connect, create a Json error.
        ObjectNode error = Json.newObject();
        error.put("error", result);

        // Send the error to the socket.
        out.write(error);
    }
}
项目:PlayTraining    文件:MessageRoom.java   
/**
 * Join the default room.
 */
public static void join(final String username, WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out)
        throws Exception {

    // Send the Join message to the room
    String result = (String) Await.result(ask(ROOM, new Join(username, out), 1000), Duration.create(1, SECONDS));

    if ("OK".equals(result)) {

        // For each event received on the socket,
        in.onMessage(new Callback<JsonNode>() {
            public void invoke(JsonNode event) {

                // Send a Talk message to the room.
                ROOM.tell(new Talk(username, event.get("text").asText()), null);

            }
        });

        // When the socket is closed.
        in.onClose(new Callback0() {
            public void invoke() {

                // Send a Quit message to the room.
                ROOM.tell(new Quit(username), null);

            }
        });
    } else {
        // Cannot connect, create a Json error.
        ObjectNode error = Json.newObject();
        error.put("error", result);

        // Send the error to the socket.
        out.write(error);
    }
}
项目:NTNU-Master-Project    文件:AssignmentController.java   
public static WebSocket<String> openEditorSocket(String pID) {
    ActorRef workspaceActor = Global.services.createEditor("10", "4");
    ActorRef webSocketActor = Akka.system().actorOf(Props.create(ServicesWebSocketActor.class, workspaceActor));

    return new WebSocket<String>() {
        public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
            webSocketActor.tell(new ServicesWebSocketActor.Init(in, out), ActorRef.noSender());
        }
    };
}
项目:vibe-examples    文件:Bootstrap.java   
public static WebSocket<String> ws() {
    final Request request = request();
    return new WebSocket<String>() {
        @Override
        public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
            wsTransportServer.on(new PlayServerWebSocket(request, in, out));
        }
    };
}
项目:masteroppgave    文件:AssignmentController.java   
public static WebSocket<String> openEditorSocket(String pID) {
    ActorRef workspaceActor = Global.services.createEditor("10", "4");
    ActorRef webSocketActor = Akka.system().actorOf(Props.create(ServicesWebSocketActor.class, workspaceActor));

    return new WebSocket<String>() {
        public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
            webSocketActor.tell(new ServicesWebSocketActor.Init(in, out), ActorRef.noSender());
        }
    };
}
项目:Hermodr-Server    文件:Session.java   
private void notifyAll(String kind, String text) {
        //TODO
//      Logger.info("notifyAll kind: " + kind + " user: " + presenter);
        for (WebSocket.Out<JsonNode> viewer : viewers.values()) {
            ObjectNode event = Json.newObject();
            event.put("kind", kind);
            event.put("data", text);

            viewer.write(event);

        }
    }
项目:Hermodr-Server    文件:Session.java   
private void updateImage(String text, int x, int y) {
    imageStrings[x][y] = text;
    for (WebSocket.Out<JsonNode> viewer : viewers.values()) {
        ObjectNode event = Json.newObject();
        event.put("kind", "sendImage");
        event.put("x", x);
        event.put("y", y);
        event.put("data", text);
        viewer.write(event);
    }
}
项目:Hermodr-Server    文件:Session.java   
private void updateAudio(String text) {
    for (WebSocket.Out<JsonNode> viewer : viewers.values()) {
        ObjectNode event = Json.newObject();
        event.put("kind", "sendAudio");
        event.put("data", text);
        viewer.write(event);
    }
}
项目:Hermodr-Server    文件:Session.java   
private void updateCursor(int x, int y) {
//      Logger.info("updateCursor kind: " + kind + " user: " + presenter + " " + x + " " + y);
        for (WebSocket.Out<JsonNode> viewer : viewers.values()) {
            ObjectNode event = Json.newObject();
            event.put("kind", "sendCursor");
            event.put("x", x);
            event.put("y", y);

            viewer.write(event);

        }
    }
项目:NationStatesPlusPlus    文件:NationStatesWebSocket.java   
@Override
public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
    try {
        this.out = out;
        // Only write out initial data for new connections, not reconnections
        if (!reconnect) {
            writeInitialData(out);
        }
        in.onMessage(new NationStatesCallback(this));
        access.getWebsocketManager().register(this, in);
    } catch (SQLException e) {
        Logger.error("Exception while setting up websocket", e);
    }
}