一、博客背景
springboot很好的封装了和集成了WebSocket,使用好这个功能可以用来实现聊天,我们都知道因为 HTTP 协议有一个缺陷:通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。要想实现只能不停连接,或者 HTTP 连接始终打开。WebSocket就可以解决这个问题。
二、springboot的WebSocket
①认识注解ServerEndpoint
这个注解可以说像control那样,修饰了才能创建socket服务,因为每一个客户端打开时,都会为其创建一个 WebSocket 对象,可以用CopyOnWriteArraySet去保存,是一个线程安全的set,用来存放每个客户端对应的 WebSocketServiceimpl 对象
连接方式
注意了这里不是http协议了,是ws协议
注意:如果使用了springboot内置的tomcat。则需要加入如下代码配置
package com.manage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
有了这个设置框架会自动寻找注解ServerEndpoint
②websocket方法
被@OnOpen修饰的方法是在连接成功的时候调用
被@OnClose修饰的方式是在断开连接的时候调用
被@OnMessage修饰的方法是在发送消息的时候调用
被@OnError是发生异常的时候调用
三、方法的参数和方法
这是session不是你想的session,是websocket连接的会话,
这个跟springboot的一样。
这个是用来发送消息的方法。
四、前端界面
①连接方式
②各种回调方法
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
innerHTML就是要显示消息
}
五、注意事项
getAsyncRemote()和getBasicRemote()是异步与同步的区别;使用任何一个的方法都会出现安全问题,会出现多个线程使用同一个session,导致出异常,
所以我们要这样写
听说getAsyncRemote()这样写也会出错。