[Spring]-spring websocket 샘플
spring mvc 는 여기 서 토론 하지 않 습 니 다.소켓 부분 을 보 세 요.
bom.xml
org.springframework
spring-core
${org.springframework.version}
org.springframework
spring-beans
${org.springframework.version}
org.springframework
spring-web
${org.springframework.version}
org.springframework
spring-webmvc
${org.springframework.mvc}
org.springframework
spring-context
${org.springframework.version}
org.springframework
spring-context-support
${org.springframework.version}
org.springframework
spring-test
${org.springframework.version}
org.springframework
spring-websocket
${org.springframework.version}
org.springframework
spring-messaging
${org.springframework.version}
spring websocket 의 핵심 은 등록 입 니 다.
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{
@Autowired
WebSocketHandler webSocketHandler;
@Autowired
HandshakeInterceptor handshakeInterceptor;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// , http https , 403 failed: Error during WebSocket handshake: Unexpected response code: 403
// String[] allowsOrigins = {"http://www.xxx.com"};
String[] allowsOrigins = {"*"};
registry.addHandler(webSocketHandler,"/appwebsocket").addInterceptors(handshakeInterceptor).setAllowedOrigins(allowsOrigins); // websocket
registry.addHandler(webSocketHandler,"/sockjs/appwebsocket").addInterceptors(handshakeInterceptor).setAllowedOrigins(allowsOrigins).withSockJS(); // websocket
}
}
그리고
handshakeInterceptor,
이것 은 악수 할 때 해 야 할 일이 다.
@Component
public class HandshakeInterceptor implements org.springframework.web.socket.server.HandshakeInterceptor{
/**
*
*/
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map attributes) throws Exception {
return true;
}
/**
*
*/
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception exception) {
}
}
다음은 웹 소켓 Handler 입 니 다.이것 은 모든 요청 의 처리 클래스 입 니 다.
@Component
@Scope("prototype")
public class WebSocketHandler implements org.springframework.web.socket.WebSocketHandler{
private static final Logger log = LoggerFactory.getLogger(WebSocketHandler.class);
@Autowired
Config config;
@Autowired
AllConnections allConnections;
@Autowired
PushCommandClient pushCommandClient;
/**
*
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
allConnections.putClientAppIoSession(session);
log.info(" 。。。 , :"+allConnections.getAppConnectionSize());
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage> socketmessage) throws Exception {
if (log.isInfoEnabled()) {
log.info("app : handleMessage app ");
}
if(socketmessage.getPayloadLength()==0){
log.info(" websocket , !!!");
return;
}
JSONObject object = JSON.parseObject(socketmessage.getPayload().toString());
// json , 。。。
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
log.error(" , ......",exception);
if(session.isOpen()){
session.close();
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
if (log.isInfoEnabled()) {
log.info("app : afterConnectionClosed , :"+allConnections.getAppConnectionSize());
}
allConnections.removeClientAppIoSession(session);
if (log.isInfoEnabled()) {
log.info("app .channel ID :"+session.getId()+" ip:"+session.getRemoteAddress()+", :"+allConnections.getAppConnectionSize());
}
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
마지막 으로 테스트 용 클 라 이언 트 코드 를 첨부 합 니 다!
webSocket
$(function(){
var websocket;
if ('WebSocket' in window) {
alert("WebSocket");
websocket = new WebSocket("ws://ip:10000/webtcpnode/appwebsocket");
} else if ('MozWebSocket' in window) {
alert("MozWebSocket");
websocket = new MozWebSocket("ws://webtcpnode/appwebsocket");
} else {
alert("SockJS");
websocket = new SockJS("http://127.0.0.1/webtcpnode/sockjs/appwebsocket/");
}
websocket.onopen = function (evnt) {
$("#tou").html(" !")
};
websocket.onmessage = function (evnt) {
$("#msg").html($("#msg").html() + "<br/>" + evnt.data);
};
websocket.onerror = function (evnt) {
};
websocket.onclose = function (evnt) {
$("#tou").html(" !")
}
$('#send').bind('click', function() {
send();
});
function send(){
if (websocket != null) {
var message = document.getElementById('message').value;
websocket.send(message);
} else {
alert(' .');
}
}
});
webSocket Demo
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.