当前位置: 首页>>代码示例>>Java>>正文


Java Session.addMessageHandler方法代码示例

本文整理汇总了Java中javax.websocket.Session.addMessageHandler方法的典型用法代码示例。如果您正苦于以下问题:Java Session.addMessageHandler方法的具体用法?Java Session.addMessageHandler怎么用?Java Session.addMessageHandler使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.websocket.Session的用法示例。


在下文中一共展示了Session.addMessageHandler方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: echoTester

import javax.websocket.Session; //导入方法依赖的package包/类
public void echoTester(String path) throws Exception {
    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("ws://localhost:" + getPort() + path));
    CountDownLatch latch =
            new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    for (String message : messages) {
        Assert.assertEquals("Hello", message);
    }
    wsSession.close();
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:26,代码来源:TestWebSocketFrameClient.java

示例2: onOpen

import javax.websocket.Session; //导入方法依赖的package包/类
@Override
    public void onOpen(Session session, EndpointConfig config) {
        System.out.println("Server session established");
        //conn to redis
        jedis = new Jedis("192.168.99.100", 6379, 10000);
        session.addMessageHandler(new MessageHandler.Whole<MeetupRSVP>() {
            @Override
            public void onMessage(MeetupRSVP message) {
                List<GroupTopic> groupTopics = message.getGroup().getGroupTopics();
                for (GroupTopic groupTopic : groupTopics) {
                    try {
                        
                        if(GROUPS_IN_REDIS.contains(groupTopic.getTopicName())){
                            jedis.zincrby(LEADERBOARD_REDIS_KEY, 1, groupTopic.getTopicName());
                        }else{
                            //zscore = jedis.zscore(LEADERBOARD_REDIS_KEY, groupTopic.getTopicName());
                            jedis.zadd(LEADERBOARD_REDIS_KEY, 1, groupTopic.getTopicName());
                            GROUPS_IN_REDIS.add(groupTopic.getTopicName());
                        }

//                        Double zscore = jedis.zscore(LEADERBOARD_REDIS_KEY, groupTopic.getTopicName());;
//                        if(zscore == null){
//                            jedis.zadd(LEADERBOARD_REDIS_KEY, 1, groupTopic.getTopicName());
//                        }else{
//                            jedis.zincrby(LEADERBOARD_REDIS_KEY, 1, groupTopic.getTopicName());
//                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        });

    }
 
开发者ID:abhirockzz,项目名称:redis-websocket-javaee,代码行数:36,代码来源:MeetupRSVPsWebSocketClient.java

示例3: testConnectToServerEndpoint

import javax.websocket.Session; //导入方法依赖的package包/类
@Test
public void testConnectToServerEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    // Set this artificially small to trigger
    // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054
    wsContainer.setDefaultMaxBinaryMessageBufferSize(64);
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());

    ((WsWebSocketContainer) wsContainer).destroy();
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:37,代码来源:TestWsWebSocketContainer.java

示例4: doTestPerMessageDefalteClient

import javax.websocket.Session; //导入方法依赖的package包/类
private void doTestPerMessageDefalteClient(String msg, int count) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME);
    List<Extension> extensions = new ArrayList<Extension>(1);
    extensions.add(perMessageDeflate);

    ClientEndpointConfig clientConfig =
            ClientEndpointConfig.Builder.create().extensions(extensions).build();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientConfig,
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(count);
    BasicText handler = new BasicText(latch, msg);
    wsSession.addMessageHandler(handler);
    for (int i = 0; i < count; i++) {
        wsSession.getBasicRemote().sendText(msg);
    }

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    ((WsWebSocketContainer) wsContainer).destroy();
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:39,代码来源:TestWsWebSocketContainer.java

示例5: onOpen

import javax.websocket.Session; //导入方法依赖的package包/类
@Override
public void onOpen(Session sn, EndpointConfig ec) {
    this.sn = sn;
    controlLatch.countDown();
    sn.addMessageHandler(String.class, s -> {
        response = s;
        controlLatch.countDown();
    });
}
 
开发者ID:abhirockzz,项目名称:websocket-chat,代码行数:10,代码来源:ChatServerTest.java

示例6: onOpen

import javax.websocket.Session; //导入方法依赖的package包/类
@Override
public void onOpen(Session sn, EndpointConfig ec) {
    try {
        sn.addMessageHandler(String.class, new MessageHandler.Whole<String>() {
            @Override
            public void onMessage(String m) {
                System.out.println("got message from server - " + m);
            }
        });
    } catch (Exception ex) {
        Logger.getLogger(WebSocketEndpointConcurrencyTest.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
开发者ID:abhirockzz,项目名称:websocket-http-session,代码行数:15,代码来源:WebSocketEndpointConcurrencyTest.java

示例7: onOpen

import javax.websocket.Session; //导入方法依赖的package包/类
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
    RemoteEndpoint.Basic remoteEndpointBasic = session.getBasicRemote();
    session.addMessageHandler(new EchoMessageHandlerText(remoteEndpointBasic));
    session.addMessageHandler(new EchoMessageHandlerBinary(remoteEndpointBasic));
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:7,代码来源:EchoEndpoint.java

示例8: doTestWriteTimeoutServer

import javax.websocket.Session; //导入方法依赖的package包/类
private void doTestWriteTimeoutServer(boolean setTimeoutOnContainer)
        throws Exception {

    // This will never work for BIO
    Assume.assumeFalse(
            "Skipping test. This feature will never work for BIO connector.",
            getProtocol().equals(Http11Protocol.class.getName()));

    /*
     * Note: There are all sorts of horrible uses of statics in this test
     *       because the API uses classes and the tests really need access
     *       to the instances which simply isn't possible.
     */
    timeoutOnContainer = setTimeoutOnContainer;

    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ConstantTxConfig.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() +
                    ConstantTxConfig.PATH));

    wsSession.addMessageHandler(new BlockingBinaryHandler());

    int loops = 0;
    while (loops < 15) {
        Thread.sleep(1000);
        if (!ConstantTxEndpoint.getRunning()) {
            break;
        }
        loops++;
    }

    // Close the client session, primarily to allow the
    // BackgroundProcessManager to shut down.
    wsSession.close();

    // Check the right exception was thrown
    Assert.assertNotNull(ConstantTxEndpoint.getException());
    Assert.assertEquals(ExecutionException.class,
            ConstantTxEndpoint.getException().getClass());
    Assert.assertNotNull(ConstantTxEndpoint.getException().getCause());
    Assert.assertEquals(SocketTimeoutException.class,
            ConstantTxEndpoint.getException().getCause().getClass());

    // Check correct time passed
    Assert.assertTrue(ConstantTxEndpoint.getTimeout() >= TIMEOUT_MS);

    // Check the timeout wasn't too long
    Assert.assertTrue(ConstantTxEndpoint.getTimeout() < TIMEOUT_MS*2);
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:64,代码来源:TestWsWebSocketContainer.java

示例9: onOpen

import javax.websocket.Session; //导入方法依赖的package包/类
@Override
public void onOpen(Session session, EndpointConfig config) {
    session.addMessageHandler(new MsgStringMessageHandler(session));
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:5,代码来源:TestEncodingDecoding.java

示例10: testBug56032

import javax.websocket.Session; //导入方法依赖的package包/类
@Test
public void testBug56032() throws Exception {
    // TODO Investigate options to get this test to pass with the HTTP BIO
    //      connector.
    Assume.assumeFalse(
            "Skip this test on BIO. TODO: investigate options to make it pass with HTTP BIO connector",
            getTomcatInstance().getConnector().getProtocolHandlerClassName().equals(
                    "org.apache.coyote.http11.Http11Protocol"));

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterFirehoseServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    clientEndpointConfig.getUserProperties().put(
            WsWebSocketContainer.SSL_TRUSTSTORE_PROPERTY,
            "test/org/apache/tomcat/util/net/ca.jks");
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("wss://localhost:" + getPort() +
                    TesterFirehoseServer.Config.PATH));

    // Process incoming messages very slowly
    MessageHandler handler = new SleepingText(5000);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    // Wait long enough for the buffers to fill and the send to timeout
    int count = 0;
    int limit = TesterFirehoseServer.WAIT_TIME_MILLIS / 100;

    System.err.println("Waiting for server to report an error");
    while (TesterFirehoseServer.Endpoint.getErrorCount() == 0 && count < limit) {
        Thread.sleep(100);
        count ++;
    }

    if (TesterFirehoseServer.Endpoint.getErrorCount() == 0) {
        Assert.fail("No error reported by Endpoint when timeout was expected");
    }

    // Wait up to another 20 seconds for the connection to be closed
    System.err.println("Waiting for connection to be closed");
    count = 0;
    limit = (TesterFirehoseServer.SEND_TIME_OUT_MILLIS * 4) / 100;
    while (TesterFirehoseServer.Endpoint.getOpenConnectionCount() != 0 && count < limit) {
        Thread.sleep(100);
        count ++;
    }

    int openConnectionCount = TesterFirehoseServer.Endpoint.getOpenConnectionCount();
    if (openConnectionCount != 0) {
        Assert.fail("There are [" + openConnectionCount + "] connections still open");
    }

    // Close the client session.
    wsSession.close();
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:70,代码来源:TestWebSocketFrameClientSSL.java

示例11: testBug58232

import javax.websocket.Session; //导入方法依赖的package包/类
@Test
public void testBug58232() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + "/echoBasic");

    Session session = null;
    try {
        session = wsContainer.connectToServer(client, uri);
        CountDownLatch latch = new CountDownLatch(1);
        BasicText handler = new BasicText(latch);
        session.addMessageHandler(handler);
        session.getBasicRemote().sendText("echoBasic");

        boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
        Assert.assertTrue(latchResult);

        Queue<String> messages = handler.getMessages();
        Assert.assertEquals(1, messages.size());
        for (String message : messages) {
            Assert.assertEquals("echoBasic", message);
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:42,代码来源:TestWsServerContainer.java

示例12: testConnectToServerEndpoint

import javax.websocket.Session; //导入方法依赖的package包/类
@Test
public void testConnectToServerEndpoint() throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterFirehoseServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("ws://localhost:" + getPort() +
                    TesterFirehoseServer.Config.PATH));
    CountDownLatch latch =
            new CountDownLatch(TesterFirehoseServer.MESSAGE_COUNT);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    System.out.println("Sent Hello message, waiting for data");

    // Ignore the latch result as the message count test below will tell us
    // if the right number of messages arrived
    handler.getLatch().await(TesterFirehoseServer.WAIT_TIME_MILLIS,
            TimeUnit.MILLISECONDS);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(
            TesterFirehoseServer.MESSAGE_COUNT, messages.size());
    for (String message : messages) {
        Assert.assertEquals(TesterFirehoseServer.MESSAGE, message);
    }
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:42,代码来源:TestWebSocketFrameClient.java

示例13: onOpen

import javax.websocket.Session; //导入方法依赖的package包/类
@Override
public void onOpen(final Session session, EndpointConfig ec) {

    log.info("Web Socket Connection opened for MC: " + this.mc.getName() + "-" + this.mc.getIpAddress());
    try {
        this.activeSession = session;
        this.mgrApi.subscribe(session);
        session.addMessageHandler(new MessageHandler.Whole<String>() {
            @Override
            public void onMessage(String text) {
                log.info("Received web socket message : " + text);
                try {
                    WebSocketClientEndPoint.this.isProcessingMessage = true;
                    MgrChangeNotification mgrChangeNotification = WebSocketClientEndPoint.this.mgrApi
                            .translateMessage(text);
                    if (mgrChangeNotification != null) {
                        WebSocketClientEndPoint.this.managerApis.triggerMcSyncService(
                                RestConstants.OSC_DEFAULT_LOGIN, WebSocketClientEndPoint.this.mc.getIpAddress(),
                                mgrChangeNotification);
                    }

                } catch (Exception ex) {
                    log.error("Failed to process notification from Manager: '"
                            + WebSocketClientEndPoint.this.mc.getName() + "-"
                            + WebSocketClientEndPoint.this.mc.getIpAddress() + "'");
                    StaticRegistry.alertGenerator().processSystemFailureEvent(SystemFailureType.MGR_WEB_SOCKET_NOTIFICATION_FAILURE,
                            new LockObjectReference(WebSocketClientEndPoint.this.mc),
                            "Failed to process notification from Manager: '"
                                    + WebSocketClientEndPoint.this.mc.getName() + "-"
                                    + WebSocketClientEndPoint.this.mc.getIpAddress() + "'");
                } finally {
                    WebSocketClientEndPoint.this.isProcessingMessage = false;
                }
            }
        });

    } catch (IOException e1) {
        log.error("Failed to subscribe notification from Manager: '" + this.mc.getName() + "'");
        StaticRegistry.alertGenerator().processSystemFailureEvent(SystemFailureType.MGR_WEB_SOCKET_NOTIFICATION_FAILURE,
                "Failed to subscribe notification from Manager: '" + this.mc.getName() + "-"
                        + this.mc.getIpAddress() + "' (" + e1.getMessage() + ")");
    }
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:44,代码来源:WebSocketClientEndPoint.java

示例14: testConnectToServerEndpointSSL

import javax.websocket.Session; //导入方法依赖的package包/类
@Test
public void testConnectToServerEndpointSSL() throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    URL truststoreUrl = this.getClass().getClassLoader().getResource(
            "org/apache/tomcat/util/net/ca.jks");
    File truststoreFile = new File(truststoreUrl.toURI());
    clientEndpointConfig.getUserProperties().put(
            WsWebSocketContainer.SSL_TRUSTSTORE_PROPERTY,
            truststoreFile.getAbsolutePath());
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("wss://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:43,代码来源:TestWsWebSocketContainer.java


注:本文中的javax.websocket.Session.addMessageHandler方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。