最近用springboot websocket试着做一个聊天系统,但是很不幸失败了,好几天了找不到解决办法,请大家帮帮忙。Thx!
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebConfig.java
@Configuration
public class WebConfig {
@Bean
public ServerEndpointExporter serverEE(){
return new ServerEndpointExporter();
}
}
MyWebsocket.java
@ServerEndpoint(value = "/websocket")
@Component
public class MyWebsocket {
@OnOpen
public void open(){
System.out.println("open");
}
@OnMessage
public void inMsg(String msg,Session session){
System.out.println("msg is :" + msg);
}
@OnClose
public void close(){
System.out.println("close now");
}
@OnError
public void error(){
System.out.println("error");
}
}
chat.html
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var ws = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
ws = new WebSocket("ws://localhost:8080/websocket");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
ws.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
ws.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
ws.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
ws.onclose = function(){
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
ws.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
//function closeWebSocket(){
// ws.close();
//}
//发送消息
function send(){
var message = document.getElementById('text').value;
ws.send(message);
}
</script>
</html>
运行时后效果:
刚打开页面连接就关闭了,请大家帮忙看下,谢谢!
看我的文档 《Netkiller Java 手札》 里面有 Spring boot 根 Websocket 的例子