(一)、添加依赖(springboot)里面整合的有WebScoket
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
(二)、创建配置类然后注入ServerEndpointExporter
ServerEndpointExporter会自动将使用了@ServerEndpoint注解的webscoket注册进来。如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理
@Configuration
public class WebScoketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
(三)、创建WebScoket类
@Slf4j
@Component
@ServerEndpoint("/webscoket")
public class WebSocket {
//用来记录当前在线连接数。增加减少连接数是线程同步的
private static int onlineCount = 0;
//每个连接通过他来传递消息:javax.websocket.Session
private Session session;
//每创建一个连接就会生成一个WebScoket,用CopyOnWriteArraySet进行保存
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
//建立连接时自动调用
@OnOpen
public void onOpen(Session session){
this.session = session;
webSockets.add(this);
addOnlineCount();
("建立连接");
}
//连接关闭时自动调用
@OnClose
public void onClose(){
webSockets.remove(this);
subOnlineCount();
("断开连接");
}
//收到消息时自动调用
@OnMessage
public void onMess(String mess){
("收到客户端发来的消息"+mess);
}
//服务器发送消息的方法
public void sendMess(String mess){
for(WebSocket webSocket : webSockets){
("{}发送消息是:{}",webSocket,mess);
try {
//发送消息
webSocket.session.getBasicRemote().sendText(mess);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
}
在别的地方调用sendMess() 发送消息
{
webSocket.sendMess("新消息");
}
(四)、客户端接受消息
var webScoket = null;
//判断浏览器是否支持webscoket
if ("WebSocket" in window){
//初始化webscoket
webScoket = new WebSocket("ws://localhost:8081/sell/webscoket")
}else {
alert("该浏览器不支持webscoket")
}
webScoket.onopen = function (event) {
console.log("建立连接")
}
webScoket.onclose = function (event) {
console.log("关闭链接")
}
webScoket.onmessage = function (event) {
console.log("收到消息"+event.data);
alert(event.data)
}
webScoket.onerror = function (event) {
console.log("发生错误")
}
//关闭窗口时断开连接关闭webscoket
window.onbeforeunload = function (ev) {
webScoket.close();
}