반응형
1). SocketHandler.java
@Component
public class SocketHandler extends TextWebSocketHandler {
HashMap<String, WebSocketSession> sessionMap = new HashMap<>(); //웹소켓 세션을 담아둘 맵
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
//메시지 발송
String msg = message.getPayload();
System.out.println("=====================MSG:"+msg+"=====================");
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//소켓 연결
System.out.println("=====================Connection Socket Success=====================");
super.afterConnectionEstablished(session);
sessionMap.put(session.getId(), session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
System.out.println("=====================Disconnection Socket Success=====================");
//소켓 종료
sessionMap.remove(session.getId());
super.afterConnectionClosed(session, status);
}
}
2).socket.js
var webSocket;
window.onload = function() {
init();
}
function init(){
webSocket = new WebSocket("ws://##IP+/webSocket");
if(webSocket){
console.log("Connection Socket Success");
}
}
function send() {
var msg = $("#message").val();
webSocket.send(msg);
$("message").val("");
}
3). WebSocketConfig
-
Spring의 경우 xml파일에 지정해서 사용할 수 있다.
-
Socket Server를 등록해준다
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{
@Autowired
SocketHandler socketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(socketHandler, "/webSocket");
}
}
반응형
'WebSocket' 카테고리의 다른 글
[WebSocket] Interceptor 사용 및 검증 절차 방법 /HttpSessionHandShakeInterceptor 사용 (0) | 2021.02.01 |
---|---|
[WebSocket] WebSocket Channeling(채널링) Java-Spring (0) | 2020.12.30 |
[WebSocket] Websocket 파라미터 전달하기(Custom Header관련) (0) | 2020.12.29 |
[WebSocket] WebSocket이란? (0) | 2020.12.29 |