一、使用Springboot內(nèi)嵌的tomcat啟動websocket
1.添加ServerEndpointExporter配置bean
@Configuration
public class WebSocketConfig {
/**
* 服務(wù)器節(jié)點
*
* 如果使用獨立的servlet容器,而不是直接使用springboot的內(nèi)置容器,就不要注入ServerEndpointExporter,因為它將由容器自己提供和管理
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.在接收連接的類加上@ServerEndpoint和@Component
@ServerEndpoint("/connect")
@Component
二菱农、使用外部tomcat容器啟動websocket
1.刪除ServerEndpointExporter配置bean
2.接收連接的類刪除@Component
三、websocket關(guān)閉連接異常
如果客戶端關(guān)閉了websocket,但服務(wù)端沒有監(jiān)聽到關(guān)閉事件究履,即onClose方法沒有調(diào)用,這是會發(fā)生的情況
此時如果服務(wù)端向客戶端推送消息脸狸,會出現(xiàn)異常告訴開發(fā)者:關(guān)閉了一個連接最仑,并重新調(diào)用onClose方法