下面列出了javax.websocket.Session#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
@Override
public void shutdown() {
synchronized (connections) {
parent.channelCloses(this);
for (final Session connection : connections) {
final ExecutorService executorService = connectionThreads.get(connection);
try {
// If there is no executor service for a client, it may has already been shut down.
if (executorService != null) {
executorService.shutdownNow();
}
connection
.close(new CloseReason(CloseCodes.GOING_AWAY, "This SynchronizeFX channel is closed now."));
} catch (final IOException e) {
callback.onClientConnectionError(connection,
new SynchronizeFXException("Failed to close the connection to a connected client.", e));
} finally {
connectionThreads.remove(connection);
}
}
connections.clear();
}
callback = null;
}
@OnOpen
public void onOpen(Session session) throws IOException{
this.session = session;
webSocketSet.add(this);
if(getOnlineCount()>0){
this.sendMessage("对不起,此服务只允许有一个连接。请稍后再试。");
session.close();
return;
}
incrOnlineCount();
logger.info("new connection...current online count: {}", getOnlineCount());
}
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendText(msg, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
@OnMessage
public void echoBinaryMessage(Session session, ByteBuffer msg,
boolean last) {
try {
session.getBasicRemote().sendBinary(msg, last);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
static void close() {
for (Session session : sessions) {
try {
session.close();
} catch (IOException ignored) {
}
}
}
@OnMessage(maxMessageSize = MAX_SIZE)
public void echoTextMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
@OnMessage
public void echoTextMessage(Session session, @SuppressWarnings("unused") String msg) {
try {
session.getBasicRemote().sendText(msg);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
private void handleOnOpenError(Session session, Throwable t) {
// If really fatal - re-throw
ExceptionUtils.handleThrowable(t);
// Trigger the error handler and close the session
onError(session, t);
try {
session.close();
} catch (IOException ioe) {
log.warn(sm.getString("pojoEndpointBase.closeSessionFail"), ioe);
}
}
@OnMessage
public void echoTextMessage(Session session, @SuppressWarnings("unused") String msg) {
try {
session.getBasicRemote().getSendWriter();
// Simulate an error
throw new RuntimeException();
} catch (IOException e) {
// Should not happen
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
@OnMessage(maxMessageSize = MAX_SIZE)
public void echoBinaryMessage(Session session, ByteBuffer msg) {
try {
session.getBasicRemote().sendBinary(msg);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
@OnMessage
public void echoBinaryMessage(Session session, ByteBuffer bb,
boolean last) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendBinary(bb, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
@Override
protected void closeConnection() throws Exception {
try {
Session session = this.session;
if (session != null && session.isOpen()) {
session.close();
}
}
finally {
this.session = null;
}
}
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendText(msg, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
@Override
protected void closeConnection() throws Exception {
try {
Session session = this.session;
if (session != null && session.isOpen()) {
session.close();
}
}
finally {
this.session = null;
}
}
private boolean validate(Session session, String ticket, Integer owner) throws IOException{
if (! ticketingServices.validateTicket(ticket, owner)){
logger.info("Invalid ticket for session " + session );
session.close( new CloseReason( CloseCodes.CANNOT_ACCEPT, "Invalid ticket"));
return false;
} else {
return true;
}
}
@Test
@Ignore // TODO Investigate why this test fails
public void testMessagesEndPoints() throws Exception {
// Set up utility classes
MessagesServer server = new MessagesServer();
SingletonConfigurator.setInstance(server);
ServerConfigListener.setPojoClazz(MessagesServer.class);
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
ctx.addApplicationListener(ServerConfigListener.class.getName());
Tomcat.addServlet(ctx, "default", new DefaultServlet());
ctx.addServletMappingDecoded("/", "default");
WebSocketContainer wsContainer =
ContainerProvider.getWebSocketContainer();
tomcat.start();
StringClient client = new StringClient();
URI uri = new URI("ws://localhost:" + getPort() + PATH_MESSAGES_EP);
Session session = wsContainer.connectToServer(client, uri);
session.getBasicRemote().sendText(MESSAGE_ONE);
// Should not take very long
int i = 0;
while (i < 20) {
if (server.received.size() > 0 && client.received.size() > 0) {
break;
}
i++;
Thread.sleep(100);
}
// Check messages were received
Assert.assertEquals(1, server.received.size());
Assert.assertEquals(1, client.received.size());
// Check correct messages were received
Assert.assertEquals(MESSAGE_ONE, server.received.peek());
session.close();
Assert.assertNull(server.t);
}
/**
* Broadcasts to a single client.
* @return true only if message appears to have been sent
*/
public static boolean broadcastToClient(String message, String clientId) {
Set<Session> invalidSessions = null;
try {
for (Map.Entry<String, ChannelInfo> channelEntry : channelMap.entrySet()) {
for (Map.Entry<Session, ChannelInfo.ClientInfo> clientEntry : channelEntry.getValue().getClientMap().entrySet()) {
Session session = clientEntry.getKey();
if (clientId.equals(session.getId())) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendText(message);
if (isDebug()) {
Debug.logInfo("Websocket: broadcasted message to client '" + clientId + "'", module);
}
return true;
} else {
if (invalidSessions == null) {
invalidSessions = new HashSet<>();
}
invalidSessions.add(session);
}
} catch (IOException e) {
if (invalidSessions == null) {
invalidSessions = new HashSet<>();
}
invalidSessions.add(session);
try {
session.close();
} catch (IOException ioe) {
if (isLog()) {
Debug.logError("Could not close websocket session: " + ioe.toString(), module);
}
}
}
return false;
}
}
}
return false;
} finally {
if (invalidSessions != null) {
removeSessions(invalidSessions);
}
}
}
@Test
public void testGetOpenSessions() 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.addServletMappingDecoded("/", "default");
tomcat.start();
WebSocketContainer wsContainer =
ContainerProvider.getWebSocketContainer();
EndpointA endpointA = new EndpointA();
Session s1a = connectToEchoServer(wsContainer, endpointA,
TesterEchoServer.Config.PATH_BASIC);
Session s2a = connectToEchoServer(wsContainer, endpointA,
TesterEchoServer.Config.PATH_BASIC);
Session s3a = connectToEchoServer(wsContainer, endpointA,
TesterEchoServer.Config.PATH_BASIC);
EndpointB endpointB = new EndpointB();
Session s1b = connectToEchoServer(wsContainer, endpointB,
TesterEchoServer.Config.PATH_BASIC);
Session s2b = connectToEchoServer(wsContainer, endpointB,
TesterEchoServer.Config.PATH_BASIC);
Set<Session> setA = s3a.getOpenSessions();
Assert.assertEquals(3, setA.size());
Assert.assertTrue(setA.remove(s1a));
Assert.assertTrue(setA.remove(s2a));
Assert.assertTrue(setA.remove(s3a));
s1a.close();
setA = s3a.getOpenSessions();
Assert.assertEquals(2, setA.size());
Assert.assertFalse(setA.remove(s1a));
Assert.assertTrue(setA.remove(s2a));
Assert.assertTrue(setA.remove(s3a));
Set<Session> setB = s1b.getOpenSessions();
Assert.assertEquals(2, setB.size());
Assert.assertTrue(setB.remove(s1b));
Assert.assertTrue(setB.remove(s2b));
// Close sessions explicitly as Gump reports a session remains open at
// the end of this test
s2a.close();
s3a.close();
s1b.close();
s2b.close();
}
@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();
}