前端需要这样写
var websocket = null;
if('WebSocket' in window){
websocket = new WebSocket('ws://izelong.natapp1.cc/webScoket');
}else{
alert("该浏览器不支持websocket!");
}
websocket.onopen = function(event){
console.log("建立连接");
}
websocket.onclose = function(event){
console.log("关闭连接");
}
websocket.onmessage = function(event){
console.log("收到消息:" + event.data);
//弹窗提醒,播放音乐
}
websocket.onerror = function(){
alert("websocket通信发生错误!");
}
window.onbeforeunload = function(){
websocket.onclose();
}
其中we://..../webSocket 服务端遵守ws协议
服务端pom.xml需要引入websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
新建service 定义接口@ServerEndpoint("/webSocket")
@ServerEndpoint("/webScoket")
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this);
log.info("【webSocket】有新的连接,总数:{}", webSocketSet.size());
}
@OnClose
public void onClose(){
webSocketSet.remove(this);
log.info("【webSocket】连接断开,总数:{}",webSocketSet.size());
}
@OnMessage
public void onMessage(String message){
log.info("【webSocket】收到客户端发来的消息:{}",message);
}
public void sendMessage(String message){
for(WebSocket webSocket:webSocketSet){
log.info("【websocket】广播消息,message:{}",message);
try{
webSocket.session.getBasicRemote().sendText(message);
} catch (IOException e){
log.error("【websocket】发送消息异常:{}",message);
e.printStackTrace();
}
}
}
}
需要序列化pojo类,idea提供了序列化插件
引入Serializable接口
idea引入Serializable插件
修改serializable插件快捷键