當前位置: 首頁>>代碼示例>>Java>>正文


Java MessageHandler類代碼示例

本文整理匯總了Java中javax.websocket.MessageHandler的典型用法代碼示例。如果您正苦於以下問題:Java MessageHandler類的具體用法?Java MessageHandler怎麽用?Java MessageHandler使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MessageHandler類屬於javax.websocket包,在下文中一共展示了MessageHandler類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: WebsocketClient

import javax.websocket.MessageHandler; //導入依賴的package包/類
public WebsocketClient(String uri, final String sessionID, MessageHandler.Whole<String> messageHandler)
    throws IOException {

// add session ID so the request gets through LAMS security
Builder configBuilder = ClientEndpointConfig.Builder.create();
configBuilder.configurator(new Configurator() {
    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
	headers.put("Cookie", Arrays.asList("JSESSIONID=" + sessionID));
    }
});
ClientEndpointConfig clientConfig = configBuilder.build();
this.websocketEndpoint = new WebsocketEndpoint(messageHandler);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
    container.connectToServer(websocketEndpoint, clientConfig, new URI(uri));
} catch (DeploymentException | URISyntaxException e) {
    throw new IOException("Error while connecting to websocket server", e);
}
   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:21,代碼來源:WebsocketClient.java

示例2: sendMessageBinary

import javax.websocket.MessageHandler; //導入依賴的package包/類
@SuppressWarnings("unchecked")
private void sendMessageBinary(ByteBuffer msg, boolean last)
        throws WsIOException {
    if (binaryMsgHandler instanceof WrappedMessageHandler) {
        long maxMessageSize =
                ((WrappedMessageHandler) binaryMsgHandler).getMaxMessageSize();
        if (maxMessageSize > -1 && msg.remaining() > maxMessageSize) {
            throw new WsIOException(new CloseReason(CloseCodes.TOO_BIG,
                    sm.getString("wsFrame.messageTooBig",
                            Long.valueOf(msg.remaining()),
                            Long.valueOf(maxMessageSize))));
        }
    }
    try {
        if (binaryMsgHandler instanceof MessageHandler.Partial<?>) {
            ((MessageHandler.Partial<ByteBuffer>) binaryMsgHandler).onMessage(msg, last);
        } else {
            // Caller ensures last == true if this branch is used
            ((MessageHandler.Whole<ByteBuffer>) binaryMsgHandler).onMessage(msg);
        }
    } catch(Throwable t) {
        handleThrowableOnSend(t);
    }
}
 
開發者ID:liaokailin,項目名稱:tomcat7,代碼行數:25,代碼來源:WsFrameBase.java

示例3: onClose

import javax.websocket.MessageHandler; //導入依賴的package包/類
@Override
public final void onClose(Session session, CloseReason closeReason) {

    if (methodMapping.getOnClose() != null) {
        try {
            methodMapping.getOnClose().invoke(pojo,
                    methodMapping.getOnCloseArgs(pathParameters, session, closeReason));
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            log.error(sm.getString("pojoEndpointBase.onCloseFail",
                    pojo.getClass().getName()), t);
        }
    }

    // Trigger the destroy method for any associated decoders
    Set<MessageHandler> messageHandlers = session.getMessageHandlers();
    for (MessageHandler messageHandler : messageHandlers) {
        if (messageHandler instanceof PojoMessageHandlerWholeBase<?>) {
            ((PojoMessageHandlerWholeBase<?>) messageHandler).onClose();
        }
    }
}
 
開發者ID:liaokailin,項目名稱:tomcat7,代碼行數:23,代碼來源:PojoEndpointBase.java

示例4: sendMessageText

import javax.websocket.MessageHandler; //導入依賴的package包/類
@SuppressWarnings("unchecked")
private void sendMessageText(boolean last) throws WsIOException {
	if (textMsgHandler instanceof WrappedMessageHandler) {
		long maxMessageSize = ((WrappedMessageHandler) textMsgHandler).getMaxMessageSize();
		if (maxMessageSize > -1 && messageBufferText.remaining() > maxMessageSize) {
			throw new WsIOException(new CloseReason(CloseCodes.TOO_BIG, sm.getString("wsFrame.messageTooBig",
					Long.valueOf(messageBufferText.remaining()), Long.valueOf(maxMessageSize))));
		}
	}

	try {
		if (textMsgHandler instanceof MessageHandler.Partial<?>) {
			((MessageHandler.Partial<String>) textMsgHandler).onMessage(messageBufferText.toString(), last);
		} else {
			// Caller ensures last == true if this branch is used
			((MessageHandler.Whole<String>) textMsgHandler).onMessage(messageBufferText.toString());
		}
	} catch (Throwable t) {
		handleThrowableOnSend(t);
	} finally {
		messageBufferText.clear();
	}
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:24,代碼來源:WsFrameBase.java

示例5: sendMessageBinary

import javax.websocket.MessageHandler; //導入依賴的package包/類
@SuppressWarnings("unchecked")
private void sendMessageBinary(ByteBuffer msg, boolean last) throws WsIOException {
	if (binaryMsgHandler instanceof WrappedMessageHandler) {
		long maxMessageSize = ((WrappedMessageHandler) binaryMsgHandler).getMaxMessageSize();
		if (maxMessageSize > -1 && msg.remaining() > maxMessageSize) {
			throw new WsIOException(new CloseReason(CloseCodes.TOO_BIG, sm.getString("wsFrame.messageTooBig",
					Long.valueOf(msg.remaining()), Long.valueOf(maxMessageSize))));
		}
	}
	try {
		if (binaryMsgHandler instanceof MessageHandler.Partial<?>) {
			((MessageHandler.Partial<ByteBuffer>) binaryMsgHandler).onMessage(msg, last);
		} else {
			// Caller ensures last == true if this branch is used
			((MessageHandler.Whole<ByteBuffer>) binaryMsgHandler).onMessage(msg);
		}
	} catch (Throwable t) {
		handleThrowableOnSend(t);
	}
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:21,代碼來源:WsFrameBase.java

示例6: onClose

import javax.websocket.MessageHandler; //導入依賴的package包/類
@Override
public final void onClose(Session session, CloseReason closeReason) {

	if (methodMapping.getOnClose() != null) {
		try {
			methodMapping.getOnClose().invoke(pojo,
					methodMapping.getOnCloseArgs(pathParameters, session, closeReason));
		} catch (Throwable t) {
			ExceptionUtils.handleThrowable(t);
			log.error(sm.getString("pojoEndpointBase.onCloseFail", pojo.getClass().getName()), t);
		}
	}

	// Trigger the destroy method for any associated decoders
	Set<MessageHandler> messageHandlers = session.getMessageHandlers();
	for (MessageHandler messageHandler : messageHandlers) {
		if (messageHandler instanceof PojoMessageHandlerWholeBase<?>) {
			((PojoMessageHandlerWholeBase<?>) messageHandler).onClose();
		}
	}
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:22,代碼來源:PojoEndpointBase.java

示例7: onOpen

import javax.websocket.MessageHandler; //導入依賴的package包/類
public void onOpen(final Session session, EndpointConfig endpointConfig) {
	session.getAsyncRemote().sendText(
			"Client Success!Your id is: " + session.getId());
	session.addMessageHandler(new MessageHandler.Whole<String>() {
		@Override
		public void onMessage(String message) {
			session.getAsyncRemote().sendObject(message, new SendHandler() {
				@Override
				public void onResult(SendResult result) {
					System.out.println(session.getId() + ":"
							+ result.isOK());
				}
			});
		}
	});
}
 
開發者ID:legend0702,項目名稱:zhq,代碼行數:17,代碼來源:WebSocketServer.java

示例8: onOpen

import javax.websocket.MessageHandler; //導入依賴的package包/類
@Override
public void onOpen(Session sn, EndpointConfig ec) {
  System.out.println("In DataMessageEndpoint#onOpen");
  this.session = sn;

  //TODO: Investgate why lambda version of the following didn't work:
  this.session.addMessageHandler(new MessageHandler.Whole<String>() {
    public void onMessage(String jsonReading) {
      try {
        ObjectMapper mapper = new ObjectMapper();
        Reading reading = mapper.readValue(jsonReading, Reading.class);
        System.out.println("New reading: " + reading.toString());
        Platform.runLater(() -> readingConsumer.setReading(reading));

      }
      catch (Exception e) {
        System.out.println("Exception: " + e.getLocalizedMessage());
      }
    }
  });
}
 
開發者ID:TRIPJavaFXClientBraintrust,項目名稱:TRIPfx,代碼行數:22,代碼來源:DataMessageEndpoint.java

示例9: debugDumpSessionInfo

import javax.websocket.MessageHandler; //導入依賴的package包/類
private void debugDumpSessionInfo() {
    if (srrp.getSessions().size() == 0) {
        Log.log(Level.FINE,this, " No sessions known.");
    }
    for (Session s : srrp.getSessions()) {
        Log.log(Level.FINE,this, " Session: " + s.getId());
        Log.log(Level.FINE,this, "   handlers: " + s.getMessageHandlers().size());
        int mhc = 0;
        for (MessageHandler m : s.getMessageHandlers()) {
            if (m instanceof SessionMessageHandler) {
                SessionMessageHandler smh = (SessionMessageHandler) m;
                Log.log(Level.FINE,this, "    [" + mhc + "] SessionMessageHandler for session " + smh.session.getId()
                        + " linked to room " + smh.owner.room.getRoomId());
            } else {
                Log.log(Level.FINE,this, "    [" + mhc + "] unknown handler");
            }
            mhc++;
        }
    }
}
 
開發者ID:gameontext,項目名稱:gameon-room,代碼行數:21,代碼來源:RoomWS.java

示例10: onOpen

import javax.websocket.MessageHandler; //導入依賴的package包/類
@Override
public void onOpen(Session session, EndpointConfig config) {
  log.debug("Session {} open on channel", session.getId());

  session.addMessageHandler(new MessageHandler.Whole<byte[]>() {

    @Override
    public void onMessage(byte[] message) {
      try {
        WebSocketEndpoint.this.onMessage(message, session);
      } catch (Exception e) {
        log.error("Unexpected exception", e);
      }
    }
  });
}
 
開發者ID:mrstampy,項目名稱:gameboot,代碼行數:17,代碼來源:WebSocketEndpoint.java

示例11: assertMessageReceived

import javax.websocket.MessageHandler; //導入依賴的package包/類
private void assertMessageReceived( String endpoint, String expectedMessage, String messageToSend ) throws Exception {
    final SettableFuture<String> futureMessage = SettableFuture.create();

    client.connectToServer( new Endpoint() {

        @Override
        public void onOpen( Session session, EndpointConfig config ) {
            clientSession = session;
            try {
                session.addMessageHandler( new MessageHandler.Whole<String>() {

                    @Override
                    public void onMessage( String message ) {
                        System.out.println( "Received message: " + message );
                        futureMessage.set( message );
                    }
                } );
                session.getBasicRemote().sendText( messageToSend );
            } catch ( IOException e ) {
                e.printStackTrace();
            }
        }
    }, cec, new URI( "ws://localhost:8025/" + endpoint ) );

    assertEquals( expectedMessage, futureMessage.get( 2, TimeUnit.SECONDS ) );
}
 
開發者ID:renatoathaydes,項目名稱:spark-ws,代碼行數:27,代碼來源:SparkWSTest.java

示例12: onOpen

import javax.websocket.MessageHandler; //導入依賴的package包/類
@Override
public void onOpen(final Session session, EndpointConfig ec) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override
        public void onMessage(String text) {
            System.out.println("Received response in client from endpoint: " + text);
        }
    });
    System.out.println("Connected to endpoint: " + session.getBasicRemote());
    try {
        String name = "Duke";
        System.out.println("Sending message from client -> endpoint: " + name);
        session.getBasicRemote().sendText(name);
    } catch (IOException ex) {
        Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
開發者ID:ftomassetti,項目名稱:JavaIncrementalParser,代碼行數:19,代碼來源:MyClient.java

示例13: onOpen

import javax.websocket.MessageHandler; //導入依賴的package包/類
@Override
public void onOpen(final Session session, EndpointConfig ec) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override
        public void onMessage(String data) {
            System.out.println("Received (MyEndpointHandler) : " + data);

            session.getAsyncRemote().sendText(data, new SendHandler() {

                @Override
                public void onResult(SendResult sr) {
                    if (sr.isOK()) {
                        System.out.println("Message written to the socket (handler)");
                    } else {
                        System.out.println("Message NOT written to the socket (handler)");
                        sr.getException().printStackTrace();
                    }

                }
            });
        }
    });
}
 
開發者ID:ftomassetti,項目名稱:JavaIncrementalParser,代碼行數:25,代碼來源:MyEndpointHandler.java

示例14: onOpen

import javax.websocket.MessageHandler; //導入依賴的package包/類
@Override
public void onOpen(Session session, EndpointConfig config) {
	final String sessionId = session.getId();
	log.info("established session with id: "+sessionId);
	
	//add text based message handler
	session.addMessageHandler(new MessageHandler.Whole<String>() {
		
		@Override
		public void onMessage(String msg) {
			log.info(sessionId+": text message: "+msg);
		}
	});
	
	//add binary based message handler
	session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {

		@Override
		public void onMessage(ByteBuffer buffer) {
			log.info(sessionId+": binary message: "+new String(buffer.array()));
		}
	});
}
 
開發者ID:nickytd,項目名稱:websocket-message-handlers-example,代碼行數:24,代碼來源:FullEchoEndpoint.java

示例15: onOpen

import javax.websocket.MessageHandler; //導入依賴的package包/類
/**
 * Callback hook for Connection open events.
 *
 * @param userSession the userSession which is opened.
 */
@Override
public void onOpen( Session userSession, EndpointConfig endpointConfig ) {
  this.userSession = userSession;
  this.userSession.setMaxTextMessageBufferSize( MAX_TXT_MSG_BUF_SIZE );
  this.userSession.setMaxBinaryMessageBufferSize( MAX_BIN_MSG_BUF_SIZE );

  userSession.addMessageHandler( new MessageHandler.Whole<Message>() {
    /**
     * Callback hook for Message Events. This method will be invoked when the server send a message.
     *
     * @param message The text message
     */
    @Override
    public void onMessage( Message message ) {
      try {
        messageEventService.fireEvent( message );
      } catch ( MessageEventFireEventException e ) {
        throw new RuntimeException( e );
      }
    }
  } );
}
 
開發者ID:pentaho,項目名稱:pentaho-kettle,代碼行數:28,代碼來源:DaemonMessagesClientEndpoint.java


注:本文中的javax.websocket.MessageHandler類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。