@OnMessage
public void msgReceived(ChatMessage msg, Session s) {
if (msg.getMsg().equals(LOGOUT_MSG)) {
try {
s.close();
return;
} catch (IOException ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
Predicate<Session> filterCriteria = null;
if (!msg.isPrivate()) {
//for ALL (except self)
filterCriteria = (session) -> !session.getUserProperties().get("user").equals(user);
} else {
String privateRecepient = msg.getRecepient();
//private IM
filterCriteria = (session) -> privateRecepient.equals(session.getUserProperties().get("user"));
}
s.getOpenSessions().stream()
.filter(filterCriteria)
//.forEach((session) -> session.getAsyncRemote().sendText(msgContent));
.forEach((session) -> session.getAsyncRemote().sendObject(new Reply(msg.getMsg(), user, msg.isPrivate())));
}
java类javax.websocket.OnMessage的实例源码
ChatServer.java 文件源码
项目:websocket-chat
阅读 28
收藏 0
点赞 0
评论 0
ConfiguratorWsServlet.java 文件源码
项目:KITE
阅读 25
收藏 0
点赞 0
评论 0
@OnMessage
public String onMessage(String message) {
List<String> splittedMessage = Arrays.asList(message.split(Pattern.quote("|")));
switch (splittedMessage.get(0)) {
case "configuration-name":
this.configName = splittedMessage.get(1);
break;
case "callback":
this.callback = splittedMessage.get(1);
break;
}
if (log.isDebugEnabled())
log.debug("Message from the client: " + message);
return this.createConfigurationText();
}
PresenceWebsocketServer.java 文件源码
项目:lams
阅读 30
收藏 0
点赞 0
评论 0
/**
* Receives a message sent by Learner via a websocket.
*
* @throws IOException
*/
@OnMessage
public void receiveRequest(String input, Session session) throws JSONException, IOException {
if (StringUtils.isBlank(input)) {
return;
}
if (input.equalsIgnoreCase("ping")) {
// just a ping every few minutes
return;
}
JSONObject requestJSON = new JSONObject(input);
switch (requestJSON.getString("type")) {
case "message":
PresenceWebsocketServer.storeMessage(requestJSON, session);
break;
case "fetchConversation":
PresenceWebsocketServer.sendConversation(requestJSON, session);
break;
}
}
LearningWebsocketServer.java 文件源码
项目:lams
阅读 25
收藏 0
点赞 0
评论 0
/**
* Receives a message sent by Learner via a websocket.
*/
@OnMessage
public void receiveRequest(String input, Session websocket) throws JSONException {
if (StringUtils.isBlank(input)) {
return;
}
if (input.equalsIgnoreCase("ping")) {
// just a ping every few minutes
return;
}
JSONObject requestJSON = new JSONObject(input);
switch (requestJSON.getString("type")) {
case "vote":
LearningWebsocketServer.vote(websocket);
break;
case "submitReport":
LearningWebsocketServer.submitReport(requestJSON, websocket);
break;
}
}
HydrographUiClientSocket.java 文件源码
项目:Hydrograph
阅读 34
收藏 0
点赞 0
评论 0
/**
*
* Called by web socket server, message contain execution tracking status that updated on job canvas.
*
* @param message the message
* @param session the session
*/
@OnMessage
public void updateJobTrackingStatus(String message, Session session) {
final String status = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
Gson gson = new Gson();
ExecutionStatus executionStatus=gson.fromJson(status, ExecutionStatus.class);
IWorkbenchPage page = PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage();
IEditorReference[] refs = page.getEditorReferences();
for (IEditorReference ref : refs){
IEditorPart editor = ref.getEditor(false);
if(editor instanceof ELTGraphicalEditor){
ELTGraphicalEditor editPart=(ELTGraphicalEditor)editor;
if(editPart.getJobId().equals(executionStatus.getJobId()) || (((editPart.getContainer()!=null) &&
(editPart.getContainer().getUniqueJobId().equals(executionStatus.getJobId()))) && editPart.getContainer().isOpenedForTracking() )){
TrackingStatusUpdateUtils.INSTANCE.updateEditorWithCompStatus(executionStatus, (ELTGraphicalEditor)editor,false);
}
}
}
}
});
}
HydrographEngineCommunicatorSocket.java 文件源码
项目:Hydrograph
阅读 25
收藏 0
点赞 0
评论 0
/**
* Client onMessage get called to kill the job
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
logger.info("Trying to kill the job");
final Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
if (execution != null) {
logger.info("Job killed successfully");
execution.kill();
timer.cancel();
}
}
};
timer.schedule(task, 0l, 600);
}
ChatServer.java 文件源码
项目:scalable-websocket-chat-with-hazelcast
阅读 28
收藏 0
点赞 0
评论 0
@OnMessage
public void msgReceived(ChatMessage msg, Session s) {
msg.from(user);
if (msg.getMsg().equals(LOGOUT_MSG)) {
try {
s.close();
return;
} catch (IOException ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
ChatEventBus.getInstance().publishChat(msg);
System.out.println("Chat Message placed on HZ Topic " + CHAT_TOPIC_NAME);
}
BroadSocket.java 文件源码
项目:JYLAND
阅读 28
收藏 0
点赞 0
评论 0
@OnMessage
public void onMessage(String message, Session session) throws IOException {
logger.info("Welcome BroadSocket onMessage " + new Date());
logger.info("Welcome BroadSocket onMessage " + message);
synchronized(clients) {
for(Session client : clients) {
if(!client.equals(session)) {
String msg=cf.rmScript(message);
logger.info("Welcome BroadSocket onMessage " + msg);
client.getBasicRemote().sendText(msg);
}
}
}
}
WebSocketController.java 文件源码
项目:cjs_ssms
阅读 24
收藏 0
点赞 0
评论 0
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
log.debug("来自客户端的消息:" + message);
/*群发消息*/
for (WebSocketController item : webSocketSet) {
try {
Principal principal = session.getUserPrincipal();
if (null == principal) {
log.debug("群发消息,未获取到当前用户认证信息。");
continue;
}
item.serializeMessage(message,principal);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
SubscriptionEndpoint.java 文件源码
项目:ccow
阅读 26
收藏 0
点赞 0
评论 0
@OnMessage
public void onWebSocketText(final Session sess, final JSONRPC2Message msg, @PathParam(CCOWContextListener.PATH_NAME) final String applicationName) {
if (msg instanceof JSONRPC2Request) {
//All operations that are invokable on ContextManager that does not return void
logger.debug("The message is a Request");
}
else if (msg instanceof JSONRPC2Notification) {
//All operations that are invokable on ContextManager that does return void
logger.debug("The message is a Notification");
}
else if (msg instanceof JSONRPC2Response) {
//All operations that are invokable from ContextManager that does not return void and are initially called from ContextManager
participant.onMessage((JSONRPC2Response) msg);
logger.debug("The message is a Response");
}
}
WSClientConnection.java 文件源码
项目:ccow
阅读 28
收藏 0
点赞 0
评论 0
@OnMessage
public void onWebSocketText(final Session sess, final JSONRPC2Message msg) throws IOException, EncodeException {
this.latestMessage = msg;
if (msg instanceof JSONRPC2Request) {
//All operations that are invokable on ContextManager that does not return void
System.out.println("The message is a Request " + msg.toJSONString());
final JSONRPC2Response data = new JSONRPC2Response(((JSONRPC2Request) msg).getID());
final Map<String,String> result = Maps.newHashMap();
result.put("decision", "valid");
result.put("reason", "");
data.setResult(result);
sess.getBasicRemote().sendObject(data);
}
else if (msg instanceof JSONRPC2Notification) {
//All operations that are invokable on ContextManager that does return void
System.out.println("The message is a Notification " + msg.toJSONString());
}
else if (msg instanceof JSONRPC2Response) {
//Can only be ContextChangesPending
System.out.println("The message is a Response " + msg.toJSONString());
}
}
MCRWebCLIResourceSockets.java 文件源码
项目:mycore
阅读 26
收藏 0
点赞 0
评论 0
@OnMessage
public void message(Session session, JsonObject request) {
sessionized(session, () -> {
LOGGER.info("Message ThreadID: {}", Thread.currentThread().getName());
LOGGER.info("MyCore Session ID (message): {}", MCRSessionMgr.getCurrentSessionID());
if (!MCRAccessManager.checkPermission("use-webcli")) {
try {
session.getBasicRemote().sendText("noPermission");
} catch (IOException ex) {
LOGGER.error("Cannot send message to client.", ex);
}
return;
}
handleMessage(session, request);
});
}
AgentEndpoint.java 文件源码
项目:atmosphere-agent
阅读 30
收藏 0
点赞 0
评论 0
@OnMessage
public void onJsonMessage(String jsonMessage, Session session) {
MessageAction messageAction = jsonUtil.getProperty(jsonMessage, JsonConst.MESSAGE_ACTION, MessageAction.class);
switch (messageAction) {
case ROUTING_ACTION:
RequestMessage request = jsonUtil.deserializeRequest(jsonMessage);
dispatcher.executeRoutingActionRequest(request);
break;
case ERROR:
ResponseMessage response = jsonUtil.deserializeResponse(jsonMessage);
LOGGER.error("Server error", response.getException());
break;
default:
LOGGER.error("Invalid message action.");
break;
}
}
WeiXinLoginEndPoint.java 文件源码
项目:javabase
阅读 27
收藏 0
点赞 0
评论 0
@OnMessage
public void handleMessage(Session session, String message) {
this.redisTemplate= SpringContextHolder.getBean("stringRedisTemplate");
log.info("input param message="+message);
//定义token 2分钟失效 失效退出循环
redisTemplate.opsForValue().set(message,LoginStatus.invalid.toString(),2, TimeUnit.MINUTES);
try {
while(true){
String code = redisTemplate.opsForValue().get(message);
if(StringUtils.isNotEmpty(code)) {
if (LoginStatus.login.toString().equals(code)){
session.getBasicRemote().sendText(new Result("0000","登录成功!",message).toJSONString());
break;
}
}else{
session.getBasicRemote().sendText(new Result("4444","网页token失效!").toJSONString());
break;
}
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
}
}
EventEndpoint.java 文件源码
项目:watchoverme-server
阅读 25
收藏 0
点赞 0
评论 0
@OnMessage
public void requestEventTracking(@PathParam("trackingPin") String trackingPin, String message, Session session) {
myLog.debug("requestEventTracking: " + trackingPin);
try {
if (session.isOpen()) {
SecqMeEventVO eventVO = eventManager.getEventByTrackingPin(trackingPin);
FullEventInfoVO eventInfoVO = eventManager.getFullEventInfoOfContact(eventVO.getId());
session.getBasicRemote().sendText(eventInfoVO.toJSON().toString());
}
} catch (IOException ex) {
myLog.error("Tracking event web socket error: " + trackingPin, ex);
try {
session.close();
} catch (IOException ex1) {
// Ignore
}
}
}
MeetingNotifier.java 文件源码
项目:sample.microprofile.meetingapp
阅读 27
收藏 0
点赞 0
评论 0
@OnMessage
public void onMessage(String id, Session s) throws IOException {
JsonObject m = manager.get(id);
if (m == null) {
s.close();
return;
}
JsonString url = m.getJsonString("meetingURL");
if (url != null) {
s.getBasicRemote().sendText(url.getString());
s.close();
return;
}
Queue<Session> sessions = listeners.get(id);
if (sessions == null) {
sessions = new ArrayBlockingQueue<>(1000);
Queue<Session> actual = listeners.putIfAbsent(id, sessions);
if (actual != null) {
sessions = actual;
}
}
sessions.add(s);
}
EventsResource.java 文件源码
项目:OpenChatAlytics
阅读 28
收藏 0
点赞 0
评论 0
/**
* Called whenever a new event is received from the compute socket
*
* @param event
* The triggering event
*/
@OnMessage
public void onMessage(ChatAlyticsEvent event) {
LOG.debug("Got realtime event: {}", event);
// don't expose package info to client
event.setClazz(null);
Set<Session> closedSessions = Sets.newHashSet();
for (Session clientSession : sessions) {
if (!clientSession.isOpen()) {
closedSessions.add(clientSession);
continue;
}
clientSession.getAsyncRemote().sendObject(event);
}
sessions.removeAll(closedSessions);
}
WSServerForIndexPage.java 文件源码
项目:tomcat-8-wffweb-demo-apps
阅读 28
收藏 0
点赞 0
评论 0
/**
* 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(byte[] message, Session session) {
browserPage.webSocketMessaged(message);
if (message.length == 0) {
LOGGER.info("client ping message.length == 0");
if (httpSession != null
&& HTTP_SESSION_HEARTBEAT_INVTERVAL < (System
.currentTimeMillis() - lastHeartbeatTime)) {
LOGGER.info("going to start httpsession hearbeat");
HeartBeatUtil.ping(httpSession.getId());
lastHeartbeatTime = System.currentTimeMillis();
}
}
}
ServerAgentEndpoint.java 文件源码
项目:atmosphere-server
阅读 30
收藏 0
点赞 0
评论 0
@OnMessage
public void onJsonMessage(String jsonMessage, Session session) {
MessageAction messageAction = jsonUtil.getProperty(jsonMessage, JsonConst.MESSAGE_ACTION, MessageAction.class);
switch (messageAction) {
case REGISTER_AGENT:
RequestMessage reqisterRequest = jsonUtil.deserializeRequest(jsonMessage);
dispatcher.registerAgent(reqisterRequest, session);
break;
case DEVICE_CHANGED:
RequestMessage deviceChangedRequest = jsonUtil.deserializeRequest(jsonMessage);
dispatcher.deviceListChanged(deviceChangedRequest);
break;
case ROUTING_ACTION:
case ERROR:
dispatcher.sendToClient(jsonMessage);
break;
default:
LOGGER.error(String.format("Unknown message action on the %s: %s",
this.getClass().getSimpleName(),
messageAction));
break;
}
}
Application.java 文件源码
项目:real1ty
阅读 36
收藏 0
点赞 0
评论 0
@OnMessage
public void receiveMessage(String message, Session session) throws IOException {
String[] contents = splitRouting(message);
// Who doesn't love switch on strings in Java 8?
switch(contents[0]) {
case "roomHello":
sessions.add(session);
addNewPlayer(session, contents[2]);
break;
case "room":
processCommand(session, contents[2]);
break;
case "roomGoodbye":
removePlayer(session, contents[2]);
break;
}
}
ServerSideSocketBdbb.java 文件源码
项目:iote2e
阅读 26
收藏 0
点赞 0
评论 0
/**
* On web socket byte.
*
* @param bytes the bytes
*/
@OnMessage
public void onWebSocketByte(byte[] bytes) {
logger.debug("onWebSocketByte len=" + bytes.length);
if (authenticated) {
try {
while (true) {
logger.debug("bytes len: " + bytes.length );
ThreadEntryPointBdbb.fromClientByteArrays.add(ByteBuffer.wrap(bytes));
break;
}
} catch (Exception e) {
logger.error("Exception decoding Iote2eRequest: {}", e.getMessage(), e);
}
} else {
logger.info("Invalid byte message, not logged in - need to force close the socket");
// TODO: force close on socket
}
}
ServerSideSocketOmh.java 文件源码
项目:iote2e
阅读 29
收藏 0
点赞 0
评论 0
/**
* On web socket byte.
*
* @param bytes the bytes
*/
@OnMessage
public void onWebSocketByte(byte[] bytes) {
logger.debug("onWebSocketByte len=" + bytes.length);
if (authenticated) {
try {
while (true) {
logger.debug("bytes len: " + bytes.length );
ThreadEntryPointOmh.fromClientByteArrays.add(ByteBuffer.wrap(bytes));
break;
}
} catch (Exception e) {
logger.error("Exception decoding Iote2eRequest: {}", e.getMessage(), e);
}
} else {
logger.info("Invalid byte message, not logged in - need to force close the socket");
// TODO: force close on socket
}
}
ClientEndpoint.java 文件源码
项目:atmosphere-client
阅读 24
收藏 0
点赞 0
评论 0
@OnMessage
public void onJsonMessage(String message, Session session) {
MessageAction messageAction = jsonUtil.getProperty(message, JsonConst.MESSAGE_ACTION, MessageAction.class);
switch (messageAction) {
case ROUTING_ACTION:
case DEVICE_ALLOCATION_INFORMATION:
case GET_ALL_AVAILABLE_DEVICES:
case ERROR:
case RELEASE_DEVICE:
ResponseMessage response = jsonUtil.deserializeResponse(message);
communicationManager.addResponse(response);
break;
default:
LOGGER.error("Unknown message action on the ClientEndpoint: " + messageAction);
break;
}
}
WebSockletRunner.java 文件源码
项目:SensorPanel
阅读 23
收藏 0
点赞 0
评论 0
@OnMessage
public void onMessage(String value) {
double temp = Double.parseDouble(value);
System.out.format("Temperature from Random service: %.2f", temp);
try {
if (temp > 30) {
yellowLed.setValue(false);
blueLed.setValue(false);
redLed.setValue(true);
} else if (temp < 10) {
yellowLed.setValue(false);
blueLed.setValue(true);
redLed.setValue(false);
} else {
yellowLed.setValue(true);
blueLed.setValue(false);
redLed.setValue(false);
}
} catch (IOException ex) {
Logger.getLogger(WebSockletRunner.class.getName()).log(Level.SEVERE, null, ex);
}
}
WebsocketClient.java 文件源码
项目:chatty
阅读 27
收藏 0
点赞 0
评论 0
@OnMessage
public synchronized void onMessage(String message, Session session) {
System.out.println("RECEIVED: " + message);
timeLastMessageReceived = System.currentTimeMillis();
handler.handleReceived(message);
receivedCount++;
try {
String[] split = message.split(" ", 3);
int id = Integer.parseInt(split[0]);
String command = split[1];
String params = "";
if (split.length == 3) {
params = split[2];
}
handleCommand(id, command, params);
} catch (ArrayIndexOutOfBoundsException | NumberFormatException ex) {
LOGGER.warning("[FFZ-WS] Invalid message: "+message);
}
}
WebsocketClient.java 文件源码
项目:chatty
阅读 35
收藏 0
点赞 0
评论 0
/**
* Receive Pong response, take the time from the payload and calculate
* latency.
*
* @param message
*/
@OnMessage
public synchronized void onPong(PongMessage message) {
try {
long timeSent = message.getApplicationData().getLong();
long latency = System.currentTimeMillis() - timeSent;
lastMeasuredLatency = latency;
timeLatencyMeasured = System.currentTimeMillis();
if (latency > 200) {
LOGGER.info(String.format("[FFZ-WS] High Latency (%dms)",
System.currentTimeMillis() - timeSent));
}
} catch (Exception ex) {
LOGGER.warning("[FFZ-WS] Invalid Pong message: "+ex);
}
}
AbstractGatewayWebSocket.java 文件源码
项目:hawkular-commons
阅读 26
收藏 0
点赞 0
评论 0
/**
* When a binary message is received from a WebSocket client, this method will lookup the {@link WsCommand} for the
* given request class and execute it.
*
* @param binaryDataStream contains the JSON request and additional binary data
* @param session the client session making the request
*/
@OnMessage
public void onBinaryMessage(InputStream binaryDataStream, Session session) {
String requestClassName = "?";
try {
// parse the JSON and get its message POJO, including any additional binary data being streamed
BasicMessageWithExtraData<BasicMessage> reqWithData = new ApiDeserializer().deserialize(binaryDataStream);
BasicMessage request = reqWithData.getBasicMessage();
requestClassName = request.getClass().getName();
log.infoReceivedBinaryData(requestClassName, session.getId(), endpoint);
handleRequest(session, reqWithData);
} catch (Throwable t) {
log.errorWsCommandExecutionFailure(requestClassName, session.getId(), endpoint, t);
String errorMessage = "BusCommand failed [" + requestClassName + "]";
sendErrorResponse(session, errorMessage, t);
}
}
AbstractGatewayWebSocket.java 文件源码
项目:hawkular-commons
阅读 24
收藏 0
点赞 0
评论 0
/**
* When a message is received from a WebSocket client, this method will lookup the {@link WsCommand} for the
* given request class and execute it.
*
* @param nameAndJsonStr the name of the API request followed by "=" followed then by the request's JSON data
* @param session the client session making the request
*/
@OnMessage
public void onMessage(String nameAndJsonStr, Session session) {
String requestClassName = "?";
try {
// parse the JSON and get its message POJO
BasicMessageWithExtraData<BasicMessage> request = new ApiDeserializer().deserialize(nameAndJsonStr);
requestClassName = request.getBasicMessage().getClass().getName();
log.infoReceivedWsMessage(requestClassName, session.getId(), endpoint);
handleRequest(session, request);
} catch (Throwable t) {
log.errorWsCommandExecutionFailure(requestClassName, session.getId(), endpoint, t);
String errorMessage = "Failed to process message [" + requestClassName + "]";
sendErrorResponse(session, errorMessage, t);
}
}
EchoEncoderEndpoint.java 文件源码
项目:sample.async.websockets
阅读 26
收藏 0
点赞 0
评论 0
/**
* Called when a message is received. The WebSocket container will take
* data from the socket, and will transform it into the parameter EchoObject
* using the {@link EchoDecoder}.
* @param o Parameters converted into an EchoObject via the <code>EchoDecoder</code>
* @param session The session associated with this message
* @throws IOException
* @throws EncodeException
*/
@OnMessage
public void receiveMessage(EchoObject o, Session session)
throws IOException, EncodeException {
// Called when a message is received.
// Single endpoint per connection by default --> @OnMessage methods are single threaded!
// Endpoint/per-connection instances can see each other through sessions.
if (o.stopRequest()) {
session.close();
} else {
// Simple broadcast
for (Session s : session.getOpenSessions()) {
s.getBasicRemote().sendObject(o);
}
}
}
EchoEndpoint.java 文件源码
项目:sample.async.websockets
阅读 28
收藏 0
点赞 0
评论 0
@OnMessage
public void receiveMessage(String message, Session session)
throws IOException {
// Called when a message is received.
// Single endpoint per connection by default --> @OnMessage methods are single threaded!
// Endpoint/per-connection instances can see each other through sessions.
if ("stop".equals(message)) {
Hello.log(this, "Endpoint " + endptId + " was asked to stop");
session.close();
} else if (message.startsWith(AnnotatedClientEndpoint.NEW_CLIENT)) {
AnnotatedClientEndpoint.connect(message);
} else {
final int id = count++;
broadcast(session, id, message); // in EchoCommon
}
}