Java javax.websocket.CloseReason 代码实例

・18 分钟阅读

以下是展示如何使用javax.websocket.CloseReason的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public static Client initializeDefault() {
  Client client = new Client();
  Consumer<Session> onOpen = (session) -> {
    log.info("Client connection opened.");
  };
  Consumer<CloseReason> onClose = (closeReason) -> {
    log.info("Client connection closed. " + closeReason);
  };
  client.onOpen(onOpen);
  client.onClose(onClose);
  return client;
}
 

实例 2


@BeforeClass
public static void setup() throws Exception {
    final ServletContainer container = ServletContainer.Factory.newInstance();
    DeploymentInfo builder = new DeploymentInfo()
            .setClassLoader(ClientEndpointReconnectTestCase.class.getClassLoader())
            .setContextPath("/ws")
            .setResourceManager(new TestResourceLoader(ClientEndpointReconnectTestCase.class))
            .setClassIntrospecter(TestClassIntrospector.INSTANCE)
            .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                    new WebSocketDeploymentInfo()
                            .setBuffers(new DefaultByteBufferPool(true, 8192))
                            .setWorker(DefaultServer.getWorker())
                            .addEndpoint(DisconnectServerEndpoint.class)
                            .addEndpoint(AnnotatedClientReconnectEndpoint.class)
                            .addListener(new WebSocketDeploymentInfo.ContainerReadyListener() {
                                @Override
                                public void ready(ServerWebSocketContainer container) {
                                    deployment = container;
                                }
                            }).setReconnectHandler(new WebSocketReconnectHandler() {
                        @Override
                        public long disconnected(CloseReason closeReason, URI connectionUri, Session session, int disconnectCount) {
                            if (disconnectCount < 3) {
                                return 1;
                            } else {
                                return -1;
                            }
                        }
                        @Override
                        public long reconnectFailed(IOException exception, URI connectionUri, Session session, int failedCount) {
                            failed = true;
                            return -1;
                        }
                    })
            )
            .setDeploymentName("servletContext.war");
    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    DefaultServer.setRootHandler(Handlers.path().addPrefixPath("/ws", manager.start()));
}
 

实例 3


@OnClose
public void sessionClosed(Session websocketSession) throws Exception {
    PlatypusServerCore platypusCore = lookupPlaypusServerCore();
    in(platypusCore, websocketSession, (com.eas.server.Session aSession) -> {
        Logger.getLogger(JsServerModuleEndPoint.class.getName()).log(Level.FINE, "Container OnClose {0}.", aSession.getId());
        JSObject closeEvent = Scripts.getSpace().makeObj();
        closeEvent.setMember("wasClean", true);
        closeEvent.setMember("code", CloseReason.CloseCodes.NORMAL_CLOSURE.getCode());
        closeEvent.setMember("reason", "");
        platypusCore.executeMethod(moduleName, WS_ON_CLOSE, new Object[]{closeEvent}, true, (Object aResult) -> {
            com.eas.server.Session session = SessionManager.Singleton.instance.remove(wasPlatypusSessionId);
            Logger.getLogger(JsServerModuleEndPoint.class.getName()).log(Level.INFO, "WebSocket platypus session closed. Session id: {0}", session.getId());
            Logger.getLogger(JsServerModuleEndPoint.class.getName()).log(Level.FINE, "{0} method of {1} module called successfully.", new Object[]{WS_ON_CLOSE, moduleName});
        }, (Exception ex) -> {
            com.eas.server.Session session = SessionManager.Singleton.instance.remove(wasPlatypusSessionId);
            Logger.getLogger(JsServerModuleEndPoint.class.getName()).log(Level.INFO, "WebSocket platypus session closed. Session id: {0}", session.getId());
            Logger.getLogger(JsServerModuleEndPoint.class.getName()).log(Level.SEVERE, null, ex);
        });
    });
}
 

实例 4


/**
 * Test of handleClosedConnection method, of class OcelotEndpoint.
 *
 * @throws java.io.IOException
 */
@Test
public void testHandleClosedConnection() throws IOException {
        System.out.println("handleClosedConnection");
        Session session = mock(Session.class);
        when(session.getId()).thenReturn(UUID.randomUUID().toString());
        when(session.isOpen()).thenReturn(true);
        CloseReason closeReason = mock(CloseReason.class);
        when(closeReason.getCloseCode()).thenReturn(CloseReason.CloseCodes.TOO_BIG);
        ocelotEndpoint.handleClosedConnection(session, closeReason);
        doThrow(IOException.class).when(session).close();
        ocelotEndpoint.handleClosedConnection(session, closeReason);
        doThrow(IllegalStateException.class).when(session).close();
        ocelotEndpoint.handleClosedConnection(session, closeReason);
        when(session.isOpen()).thenReturn(false);
        ocelotEndpoint.handleClosedConnection(session, closeReason);
}
 

实例 5


/**
 * Method handles Grizzly {@link Connection} close phase. Check if the {@link Connection} is a {@link org.glassfish.tyrus.core.TyrusWebSocket}, if
 * yes - tries to close the websocket gracefully (sending close frame) and calls {@link
 *
 * @param ctx {@link FilterChainContext}
 * @return {@link NextAction} instruction for {@link FilterChain}, how it should continue the execution
 * @throws IOException
 */
@Override
public NextAction handleClose(FilterChainContext ctx) throws IOException {
    final org.glassfish.tyrus.spi.Connection connection = getConnection(ctx);
    if (connection != null) {
        taskQueue.add(new CloseTask(connection, new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, null), ctx.getConnection()));
        TaskProcessor.processQueue(taskQueue, null);
    }
    return ctx.getStopAction();
}
 

实例 6


@Override
public Endpoint endpoint() {
    final JavaxWebsocketChannel channel = this;
    return new Endpoint() {
        @Override
        public void onOpen(final Session session, final EndpointConfig endpointConfig) {
            session.addMessageHandler(new MessageHandler.Whole<String>() {
                @Override
                public void onMessage(String s) {
                    notifyMessage(s);
                }
            });
            session.addMessageHandler(new MessageHandler.Whole<byte[]>() {
                @Override
                public void onMessage(byte[] s) {
                    notifyMessage(s);
                }
            });
            channel.setUnderlyingChannel(session);
            channel.notifyOpen(endpointConfig);
        }
        @Override
        public void onClose(final Session _, final CloseReason closeReason) {
            notifyClose(closeReason.getCloseCode().getCode(),
                        closeReason.getReasonPhrase());
        }
        @Override
        public void onError(final Session _, final Throwable error) {
            notifyError(error);
        }
    };
}
 

实例 7


/**
 * Is called when a web socket session is closing.
 *
 * @param session
 *       Web socket session.
 * @param closeReason
 *       The reason why a web socket has been closed, or why it is being asked to close
 */
@OnClose
public void onClose(final Session session, final CloseReason closeReason) {
   if (logger.isTraceEnabled()) {
      logger.trace(String.format("Session %s closed because of %s", session.getId(), closeReason));
   }
}
 

实例 8


@SuppressWarnings("unchecked")
private void didMessage(String payload) {
    if (ws != null && session != null && payload.length() > 0) {
        if (payload.charAt(0) == '[') {
            List<String> messages;
            try {
                messages = Utils.parseJson(payload, List.class);
            } catch (Exception x) {
                try {
                    ws.close(new CloseReason(CloseReason.CloseCodes.PROTOCOL_ERROR, "Broken framing"));
                } catch (IOException e) {}
                return;
            }
            for (String message : messages) {
                session.didMessage(message);
            }
        } else {
            String message;
            try {
                message = Utils.parseJson(payload, String.class);
            } catch (Exception x) {
                try {
                    ws.close(new CloseReason(CloseReason.CloseCodes.PROTOCOL_ERROR, "Broken framing"));
                } catch (IOException e) {}
                return;
            }
            session.didMessage(message);
        }
    }
}
 

实例 9


@Override
public void onError(final Session session, final Throwable throwable) {
        LOG.log(Level.WARNING, "Websocket connection error:", throwable);
        if (throwable instanceof SocketTimeoutException) {
                transport.onClose(session, new CloseReason(
                                CloseReason.CloseCodes.CLOSED_ABNORMALLY,
                                "Timeout on Socket!"));
        }
        if (throwable instanceof EOFException) {
                transport.onClose(session, new CloseReason(
                                CloseReason.CloseCodes.CLOSED_ABNORMALLY, "EOF!"));
        }
}
 

实例 10


@Test
public void testWebsockets1() throws Exception {
    Session session = ContainerProvider.getWebSocketContainer().connectToServer(ClientEndpointImpl.class, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/websocket1"));
    Assert.assertEquals("connected", messages.poll(5, TimeUnit.SECONDS));
    session.getBasicRemote().sendText("test1");
    Assert.assertEquals("echo-test1", messages.poll(5, TimeUnit.SECONDS));
    byte[] data = new byte[1000];
    for(int i = 0; i < 100; ++i) {
        data[i] = (byte)i;
    }
    session.getBasicRemote().sendBinary(ByteBuffer.wrap(data));
    Assert.assertArrayEquals(data, binaryMessages.poll(5, TimeUnit.SECONDS));
    session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "foo"));
}
 

实例 11


public void openSession(Session session, String ticket) {
  try {
    WebSocketTicket ticket1 = webSocketTicketController.findTicket(ticket);
    if (verifyTicket(ticket1)) {
      session.getUserProperties().put("UserId", ticket1.getUser());
      sessions.put(ticket, session);
    } else {
      try {
        session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Ticket could not be validated."));
      } catch (Exception e) {
        // Closing failed, ignore
      }
    }
  } catch (Exception e) {
    logger.log(Level.SEVERE, "Failed to open WebSocket session", e);
  }
}
 

实例 12


@OnOpen
public void open(final Session session) {
    try {
        session.getBasicRemote().sendText("websocket");
    } catch (IOException e) {
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.PROTOCOL_ERROR, "Should be able to send a message"));
        } catch (final IOException e1) {
            throw new IllegalStateException(e1);
        }
    }
}
 

实例 13


@Override
protected void shutdown(String reason)
{
    Session session;
    synchronized (this)
    {
        session = _session;
        close();
    }
    if (session != null)
    {
        if (logger.isDebugEnabled())
            logger.debug("Closing ({}) websocket session {}", reason, session);
        try
        {
            // Limits of the WebSocket APIs, otherwise an exception is thrown.
            reason = reason.substring(0, Math.min(reason.length(), 30));
            session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, reason));
        }
        catch (Throwable x)
        {
            logger.trace("Could not close websocket session " + session, x);
        }
    }
}
 

实例 14


public void close(boolean timeout) {
       log.debug("Channel %s close%s (was %s)", getId(), timeout ? " (timeout)" : "", session == null ? "(no session)" : (session.isOpen() ? "(open)" : "(not open)"));
        if (session != null) {
           try {
                if (timeout)
                        session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "Idle timeout"));
                else
                session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Channel closed"));
           }
           catch (Exception e) {
                log.error(e, "Could not close channel %s", getId());
               throw new RuntimeException("Channel close error " + getId(), e);
           }
           session = null;
        }
}
 

实例 15


@Test
public void codec() throws Exception {
    JsrClientEndpointImpl.MESSAGES.clear();
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    final Session session = container.connectToServer(
            JsrClientEndpointImpl.class,
            new URI("ws://localhost:" + url.getPort() + url.getPath() + "jsrserver"));
    session.getBasicRemote().sendObject(Json.createObjectBuilder().add("value", "[email protected]").build());
    JsrClientEndpointImpl.SEMAPHORE.acquire();
    // it does wait for the server, using same jaxrs provider to match format, it uses jettison which is weird but we don't care for that part of test
    final JsonObject serverMessage = Json.createReader(new URL(url.toExternalForm() + "report/jsr").openStream()).readObject();
    session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "bye"));
    assertNotNull(serverMessage);
    assertEquals("[email protected]", serverMessage.getString("value"));
    assertEquals(1, JsrClientEndpointImpl.MESSAGES.size());
    assertEquals("[email protected]", JsrClientEndpointImpl.MESSAGES.iterator().next().getString("value"));
}
 
讨论
淘淘あ西西 profile image