환경
: 스프링 레거시, Maven, 자바 설정
전체 코드
[WebSocketConfig.java]
: WebSocketConfig implements WebSocketConfigurer
@Configuration
@RequiredArgsConstructor
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{
private final MyWebSocketHandler myWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler, "/chatting")
.addInterceptors(new HttpSessionHandshakeInterceptor())
.setAllowedOrigins("*");
}
}
[WebConfig.java]
: WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer
@Configuration
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ServletConfig.class, WebSocketConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
registration.setInitParameter("dispatchOptionsRequest", "true");
registration.setLoadOnStartup(1);
}
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
return new Filter[] {encodingFilter};
}
}
[MyWebSocketHandler.java]
: MyWebSocketHandler extends TextWebSocketHandler
@Controller
public class MyWebSocketHandler extends TextWebSocketHandler {
List<WebSocketSession> sessionList = new ArrayList<>();
//소켓 open
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("연결됨... =>" + session);
sessionList.add(session);
}
//전체채팅
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
System.out.println(("id로 부터 message 받음 =>"+ session.getId()+ message.getPayload()));
for (WebSocketSession s : sessionList) {
s.sendMessage(new TextMessage(session.getId() + " : " + message.getPayload()));
}
}
// 소켓 close
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessionList.remove(session);
System.out.println("연결 해제..... =>" + session + " : " + session.getId());
}
}
[ChatController.java]
@Controller
@Log4j
@RequestMapping("/chat/*")
@AllArgsConstructor
public class ChatController {
@RequestMapping(value= "/chatting", method = { RequestMethod.GET })
public String chat() {
return "/chat/chatting";
}
}
[.jsp]
<script type="text/javascript">
var ws;
$(document).ready(function() {
connect();
});
function connect() {
ws = new WebSocket("ws://localhost:8011/controller/chatting");
ws.onopen = function() {
console.log('socket opend')
};
ws.onmessage = function(event) {
console.log(".....onmessage" + event.data)
};
ws.onclose = function(event) {
console.log('socket closed')
}
}
$('button').on("click", function(e){
e.preventDefault();
var msg = document.getElementById("inputmessage").value;
ws.send(msg);
msg = "";
});
</script>
</head>
<body>
<div>
<input type="text" id="inputmessage">
</div>
<button type="button">메세지 전송</button>
</body>
</html>
'SPRING' 카테고리의 다른 글
SPRING 웹소켓에서 HttpSession 값 불러오기 (0) | 2023.02.19 |
---|---|
SPRING mybatis <selectKey> (0) | 2023.02.13 |
SPRING 의존성 주입 (0) | 2023.02.08 |
SPRING 테스트 코드 작성 (0) | 2023.02.07 |
SPRING 설정 (JAVA Configuration) (0) | 2023.02.06 |