spring-boot/spring-boot-samples/spring-boot-sample-websocket/src/main/java/samples/websocket/client/SimpleClientWebSocketHandle...

58 lines
1.8 KiB
Java
Raw Normal View History

2013-08-06 00:50:24 +08:00
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2013-10-09 11:25:10 +08:00
package samples.websocket.client;
2013-08-06 00:50:24 +08:00
import java.util.concurrent.CountDownLatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
2013-12-04 03:51:51 +08:00
import org.springframework.web.socket.handler.TextWebSocketHandler;
2013-08-06 00:50:24 +08:00
2013-12-04 03:51:51 +08:00
public class SimpleClientWebSocketHandler extends TextWebSocketHandler {
2013-08-06 00:50:24 +08:00
protected Log logger = LogFactory.getLog(SimpleClientWebSocketHandler.class);
private final GreetingService greetingService;
private CountDownLatch latch;
@Autowired
2013-10-09 11:25:10 +08:00
public SimpleClientWebSocketHandler(GreetingService greetingService,
CountDownLatch latch) {
2013-08-06 00:50:24 +08:00
this.greetingService = greetingService;
this.latch = latch;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
TextMessage message = new TextMessage(this.greetingService.getGreeting());
session.sendMessage(message);
}
@Override
2013-10-09 11:25:10 +08:00
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
this.logger.info("Received: " + message + " (" + this.latch.getCount() + ")");
2013-08-06 00:50:24 +08:00
session.close();
2013-10-09 11:25:10 +08:00
this.latch.countDown();
2013-08-06 00:50:24 +08:00
}
}