Springboot基于websocket实现简单在线聊天功能
添加maven依赖
org.springframework.boot spring-boot-starter-parent 2.2.5.RELEASE 4.0.0 springboot-websocket springboot-websocket org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-websocket
添加websocket配置
@Configuration @EnableWebSocket publicclassMyWebSocketConfigimplementsWebSocketConfigurer{ @Override publicvoidregisterWebSocketHandlers(WebSocketHandlerRegistryregistry){ registry.addHandler(myHandler(),"/myHandler").setAllowedOrigins("*"); } @Bean publicWebSocketHandlermyHandler(){ returnnewMyTextWebSocketHandler(); } }
实现具体的handler
publicclassMyTextWebSocketHandlerextendsTextWebSocketHandler{ privateSetsessions=newHashSet<>(); @Override protectedvoidhandleTextMessage(WebSocketSessionsession,TextMessagemessage)throwsException{ if(session.isOpen()){ sessions.add(session); } sendToAll(message); } privatevoidsendToAll(TextMessagemessage)throwsIOException{ for(WebSocketSessionsession:sessions){ session.sendMessage(message); } } @Override publicvoidafterConnectionClosed(WebSocketSessionsession,CloseStatusstatus)throwsException{ sessions.remove(session); } }
即可通过ws://localhost:8080/myHandler访问websocket
添加测试页面:
if("WebSocket"inwindow){ varws=newWebSocket("ws://localhost:8080/myHandler"); ws.onopen=function(){ }; ws.onmessage=function(evt){ document.getElementById('messageDiv').innerHTML+=evt.data+""; }; ws.onclose=function(){ console.log("closeconnect"); }; }else{ alert("您的浏览器不支持WebSocket!"); } functionsend(){ ws.send(document.getElementById("input").value+":"+document.getElementById("message").value); } 当前用户:
发送消息: