下面列出了java.nio.channels.WritePendingException#javax.websocket.CloseReason 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Cleans up the resources still in use by WebSocket sessions created from
* this container. This includes closing sessions and cancelling
* {@link Future}s associated with blocking read/writes.
*/
public void destroy() {
CloseReason cr = new CloseReason(
CloseCodes.GOING_AWAY, sm.getString("wsWebSocketContainer.shutdown"));
for (WsSession session : sessions.keySet()) {
try {
session.close(cr);
} catch (IOException ioe) {
log.debug(sm.getString(
"wsWebSocketContainer.sessionCloseFail", session.getId()), ioe);
}
}
// Only unregister with AsyncChannelGroupUtil if this instance
// registered with it
if (asynchronousChannelGroup != null) {
synchronized (asynchronousChannelGroupLock) {
if (asynchronousChannelGroup != null) {
AsyncChannelGroupUtil.unregister();
asynchronousChannelGroup = null;
}
}
}
}
@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) {
log.error(sm.getString("pojoEndpointBase.onCloseFail",
pojo.getClass().getName()), t);
handleOnOpenOrCloseError(session, 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();
}
}
}
/**
* Cleans up the resources still in use by WebSocket sessions created from
* this container. This includes closing sessions and cancelling
* {@link Future}s associated with blocking read/writes.
*/
public void destroy() {
CloseReason cr = new CloseReason(
CloseCodes.GOING_AWAY, sm.getString("wsWebSocketContainer.shutdown"));
for (WsSession session : sessions.keySet()) {
try {
session.close(cr);
} catch (IOException ioe) {
log.debug(sm.getString(
"wsWebSocketContainer.sessionCloseFail", session.getId()), ioe);
}
}
// Only unregister with AsyncChannelGroupUtil if this instance
// registered with it
if (asynchronousChannelGroup != null) {
synchronized (asynchronousChannelGroupLock) {
if (asynchronousChannelGroup != null) {
AsyncChannelGroupUtil.unregister();
asynchronousChannelGroup = null;
}
}
}
}
/**
* Callback hook for Connection close events.
*
* @param userSession
* the userSession which is getting closed.
* @param reason
* the reason for connection close
*/
@OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println(
"WebsocketClientEndpoint.onClose(): Closing Websocket.... Reason[" + reason.getReasonPhrase() + "]");
try {
this.userSession.close();
} catch (IOException e) {
System.out.println("WebsocketClientEndpoint.onClose(): ERROR: IOException on userSession close!!!");
e.printStackTrace();
}
this.userSession = null;
// stop timer if running
if (hbTimer != null) {
hbTimer.cancel();
hbTimer = null;
}
// Notify session closed
sessionNotifier.notifyWsSessionClosed(terminate);
}
@Override
public void onClose(Session session, CloseReason closeReason) {
Room room = getRoom(false);
if (room != null) {
room.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
// Player can be null if it couldn't enter the room
if (player != null) {
// Remove this player from the room.
player.removeFromRoom();
// Set player to null to prevent NPEs when onMessage events
// are processed (from other threads) after onClose has been
// called from different thread which closed the Websocket session.
player = null;
}
} catch (RuntimeException ex) {
log.error("Unexpected exception: " + ex.toString(), ex);
}
}
});
}
}
public static Client initializeDefault() {
Client client = new Client();
Consumer<Session> onOpen = (session) -> {
LOGGER.info("Client connection opened.");
};
Consumer<CloseReason> onClose = (closeReason) -> {
LOGGER.info("Client connection closed. " + closeReason);
};
client.onOpen(onOpen);
client.onClose(onClose);
return client;
}
/**
* Try sending the {@link Message} using
* {@link Session#getBasicRemote()}, {@link Basic#sendObject(Object)}.
*
* @param session Session to send the message on
* @param message Message to send
* @return true if send was successful, or false if it failed
*/
private boolean sendMessageToSession(Session session, Message message) {
if (session.isOpen()) {
try {
session.getBasicRemote().sendObject(message);
return true;
} catch (EncodeException e) {
// Something was wrong encoding this message, but the connection
// is likely just fine.
Log.log(Level.FINE, this, "Unexpected condition writing message", e);
} catch (IOException ioe) {
// An IOException, on the other hand, suggests the connection is
// in a bad state.
Log.log(Level.FINE, this, "Unexpected condition writing message", ioe);
tryToClose(session, new CloseReason(CloseCodes.UNEXPECTED_CONDITION, trimReason(ioe.toString())));
}
}
return false;
}
@OnClose
public void unregisterUser(Session websocket, CloseReason reason) throws IOException {
String login = websocket.getUserPrincipal().getName();
if (login == null) {
return;
}
Integer organisationId = Integer
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0));
KumaliveDTO kumalive = kumalives.get(organisationId);
if (kumalive == null) {
return;
}
KumaliveWebsocketServer.unregisterUser(kumalive, login);
KumaliveWebsocketServer.sendRefresh(kumalive);
}
/**
* Called when a close message is received. Should only ever happen once.
* Also called after a protocol error when the ProtocolHandler needs to
* force the closing of the connection.
*/
public void onClose(CloseReason closeReason) {
synchronized (stateLock) {
if (state != State.CLOSED) {
try {
wsRemoteEndpoint.setBatchingAllowed(false);
} catch (IOException e) {
log.warn(sm.getString("wsSession.flushFailOnClose"), e);
fireEndpointOnError(e);
}
if (state == State.OPEN) {
state = State.OUTPUT_CLOSED;
sendCloseMessage(closeReason);
fireEndpointOnClose(closeReason);
}
state = State.CLOSED;
// Close the socket
wsRemoteEndpoint.close();
}
}
}
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;
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
HttpSessionImpl session = (HttpSessionImpl) se.getSession();
final Session underlying;
if (System.getSecurityManager() == null) {
underlying = session.getSession();
} else {
underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
}
List<UndertowSession> connections = (List<UndertowSession>) underlying.getAttribute(SESSION_ATTRIBUTE);
if (connections != null) {
synchronized (underlying) {
for (UndertowSession c : connections) {
try {
c.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, ""));
} catch (IOException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
}
}
}
}
}
@Test
public void testCloseReason() throws Exception {
AnnotatedClientEndpoint.reset();
MessageEndpoint.reset();
Session session = deployment.connectToServer(AnnotatedClientEndpoint.class, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/chat/Bob"));
Assert.assertEquals("hi Bob (protocol=foo)", AnnotatedClientEndpoint.message());
session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "Foo!"));
Assert.assertEquals("CLOSED", AnnotatedClientEndpoint.message());
CloseReason cr = MessageEndpoint.getReason();
Assert.assertEquals(CloseReason.CloseCodes.VIOLATED_POLICY.getCode(), cr.getCloseCode().getCode());
Assert.assertEquals("Foo!", cr.getReasonPhrase());
}
@Test
@DisplayName("Players can have multiple sessions, verify they are all closed")
void allSameNamePlayersAreDisconnected() throws Exception {
when(session.getId()).thenReturn("1");
when(session2.getId()).thenReturn("2");
chatters.connectPlayer(buildChatterSession(session));
chatters.connectPlayer(buildChatterSession(session2));
final boolean result =
chatters.disconnectPlayerByName(CHAT_PARTICIPANT.getUserName(), "disconnect message");
assertThat(result, is(true));
verify(session).close(any(CloseReason.class));
verify(session2).close(any(CloseReason.class));
}
private void onError(Throwable throwable) {
wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, throwable.getMessage()),
new CloseReason(CloseCodes.CLOSED_ABNORMALLY, throwable.getMessage()));
// Need to call onError using the web application's class loader
Thread t = Thread.currentThread();
ClassLoader cl = t.getContextClassLoader();
t.setContextClassLoader(applicationClassLoader);
try {
ep.onError(wsSession, throwable);
} finally {
t.setContextClassLoader(cl);
}
}
protected void sendMessage(String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException ioe) {
CloseReason cr =
new CloseReason(CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage());
try {
session.close(cr);
} catch (IOException ioe2) {
// Ignore
}
}
}
private void closeWithError(Session session, String roundId, String msg) throws IOException {
log(roundId, msg);
sendToClient(session, new OutboundMessage.ErrorEvent(msg));
// close reason phrase cannot exceed 123 UTF-8 encoded bytes
if (msg.length() > 123)
msg = msg.substring(0, 122);
session.close(new CloseReason(CloseCodes.UNEXPECTED_CONDITION, msg));
}
@Override
@OnClose
public void onClose(Session session, CloseReason closeReason) {
try {
if (tunnel != null)
tunnel.close();
}
catch (GuacamoleException e) {
logger.debug("Unable to close WebSocket tunnel.", e);
}
}
protected void checkExpiration() {
long timeout = maxIdleTimeout;
if (timeout < 1) {
return;
}
if (System.currentTimeMillis() - lastActive > timeout) {
String msg = sm.getString("wsSession.timeout");
doClose(new CloseReason(CloseCodes.GOING_AWAY, msg),
new CloseReason(CloseCodes.CLOSED_ABNORMALLY, msg));
}
}
protected void checkExpiration() {
long timeout = maxIdleTimeout;
if (timeout < 1) {
return;
}
if (System.currentTimeMillis() - lastActive > timeout) {
String msg = sm.getString("wsSession.timeout", getId());
if (log.isDebugEnabled()) {
log.debug(msg);
}
doClose(new CloseReason(CloseCodes.GOING_AWAY, msg),
new CloseReason(CloseCodes.CLOSED_ABNORMALLY, msg));
}
}
private void handleThrowableOnSend(Throwable t) throws WsIOException {
ExceptionUtils.handleThrowable(t);
wsSession.getLocal().onError(wsSession, t);
CloseReason cr = new CloseReason(CloseCodes.CLOSED_ABNORMALLY,
sm.getString("wsFrame.ioeTriggeredClose"));
throw new WsIOException(cr);
}
@Override
protected void onClose(CloseReason closereason) {
edm.countOpened.ifPresent(Counter::dec);
Timer.Context ctx = (Timer.Context) getJsrSession().getUserProperties().get(this.getClass().getName());
if (ctx != null)
ctx.close();
super.onClose(closereason);
}
private static Object[] buildArgs(PojoPathParam[] pathParams,
Map<String,String> pathParameters, Session session,
EndpointConfig config, Throwable throwable, CloseReason closeReason)
throws DecodeException {
Object[] result = new Object[pathParams.length];
for (int i = 0; i < pathParams.length; i++) {
Class<?> type = pathParams[i].getType();
if (type.equals(Session.class)) {
result[i] = session;
} else if (type.equals(EndpointConfig.class)) {
result[i] = config;
} else if (type.equals(Throwable.class)) {
result[i] = throwable;
} else if (type.equals(CloseReason.class)) {
result[i] = closeReason;
} else {
String name = pathParams[i].getName();
String value = pathParameters.get(name);
try {
result[i] = Util.coerceToType(type, value);
} catch (Exception e) {
throw new DecodeException(value, sm.getString(
"pojoMethodMapping.decodePathParamFail",
value, type), e);
}
}
}
return result;
}
@Override
public void onDataAvailable() {
try {
wsFrame.onDataAvailable();
} catch (WsIOException ws) {
wsProtocolHandler.close(ws.getCloseReason());
} catch (IOException ioe) {
onError(ioe);
CloseReason cr = new CloseReason(
CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage());
wsProtocolHandler.close(cr);
}
}
protected void sendMessage(String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException ioe) {
CloseReason cr =
new CloseReason(CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage());
try {
session.close(cr);
} catch (IOException ioe2) {
// Ignore
}
}
}
@Override
public void onClose(Session session, CloseReason closeReason) {
try {
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@OnOpen
public void registerUser(Session websocket) throws IOException {
Integer organisationId = Integer
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0));
Integer userId = getUser(websocket).getUserId();
if (!KumaliveWebsocketServer.getSecurityService().hasOrgRole(organisationId, userId,
new String[] { Role.GROUP_MANAGER, Role.MONITOR, Role.LEARNER }, "register on kumalive", false)) {
// prevent unauthorised user from accessing Kumalive
String warning = "User " + userId + " is not a monitor nor a learner of organisation " + organisationId;
logger.warn(warning);
websocket.close(new CloseReason(CloseCodes.CANNOT_ACCEPT, warning));
}
}
@OnClose
public void onClose(@PathParam("name") String name, CloseReason closeReason, WebSocketConnection webSocketConnection) {
LOGGER.info("Connection is closed with status code : " + closeReason.getCloseCode().getCode()
+ " On reason " + closeReason.getReasonPhrase());
webSocketConnections.remove(webSocketConnection);
String msg = name + " left the chat";
sendMessageToAll(msg);
}
@Override
public void onClose(Session session, CloseReason closeReason) {
System.out.println("close. "+closeReason);
log.interesting("Websocket session "+session.getId()+" closed "+closeReason
+" with client instance "+LibertyClientInstance.getInstance().getUuid(), clientState.getLogContext());
sessionWrapper.onDisconnect(session);
ResourceLifecycleUtil.getInstance().removeSession(ClientUtil.convertSessionToManagedResource(session));
}
@Override
public Mono<Void> close(CloseStatus status) {
try {
CloseReason.CloseCode code = CloseCodes.getCloseCode(status.getCode());
getDelegate().close(new CloseReason(code, status.getReason()));
}
catch (IOException ex) {
return Mono.error(ex);
}
return Mono.empty();
}
private void doClose() {
closed = true;
for (ConfiguredServerEndpoint endpoint : configuredServerEndpoints) {
for (Session session : endpoint.getOpenSessions()) {
try {
session.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, ""));
} catch (Exception e) {
JsrWebSocketLogger.ROOT_LOGGER.couldNotCloseOnUndeploy(e);
}
}
}
}