需要引入的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
后端需要增加两个类
package com.cn.visualWeb.websocket;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint(value = "/websocket")
public class CommWebSocketServer {
private static CopyOnWriteArraySet<CommWebSocketServer> webSocketSet = new CopyOnWriteArraySet<CommWebSocketServer>();
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
System.out.println("有新连接加入!当前在线人数为" + webSocketSet.size());
try {
sendMessage("连接成功,当前时间:" + new java.sql.Timestamp(System.currentTimeMillis()));
} catch (IOException e) {
System.out.println("IO异常");
}
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
System.out.println("有一连接关闭!当前在线人数为" + webSocketSet.size());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
for (CommWebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static void sendInfo(Map<String,Object> param) throws IOException {
for (CommWebSocketServer item : webSocketSet) {
try {
item.sendMessage(JSONObject.toJSONString(param));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cn.visualWeb.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class CommWebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
前端js调用
var websocket = null;
if('WebSocket' in window){
websocket = new WebSocket("ws://127.0.0.1:8080/websocket");
}
else{
alert('Not support websocket')
}
websocket.onerror = function(){
console.log("error");
};
websocket.onopen = function(event){
console.log("open");
}
websocket.onmessage = function (event) {
console.log(event.data);
}
websocket.onclose = function(){
console.log("close");
}
window.onbeforeunload = function(){
websocket.close();
}
function closeWebSocket(){
websocket.close();
}
function send(){
websocket.send("消息内容");
}