内容来源:点击跳转
主要是这个依赖。
<!--socket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class Configure{
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
websocket 类
当然,若不做人数,统计可去掉。
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/websocket/{sid}")
public class WebSocket {
static Log log = LogFactory.getLog(WebSocket.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static volatile int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的Socket对象。
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<WebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
@OnOpen
public void open(Session session,@PathParam("sid") String sid){
this.session = session;
webSockets.add(this);
addOnlineCount(); //在线人数+1
log.info("有新窗口开始监听:"+sid+" 当前在线人数为" + getOnlineCount());
//sendMessage("已成功建立连接!");
}
@OnClose
public void close(Session session){
webSockets.remove(this);
subOnlineCount(); //在线人数-1
}
@OnMessage
public void message(String message){
//收到客户端消息后调用的方法
for (WebSocket item : webSockets) {
item.sendMessage(message);
}
}
public void sendMessage(String message){
try{
this.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInfoToAll(String message){
for (WebSocket item : webSockets) {
//这里全部推送,单独发送需要判断sid
item.sendMessage(message);
}
}
@OnError
public void error(Session session,Throwable error){
error.printStackTrace();
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
}
controller
@Controller
public class AccessController {
@RequestMapping("/")
public String index(){
return "index";
}
@Scheduled(fixedRate = 3000)
@GetMapping("/visual")
@ResponseBody
public List<Integer> visual(){
List<Integer> collect = Arrays.stream("30,5,20,40,23,50".split(",")).map(element -> (int)(Math.random() * 50 + 1)).collect(Collectors.toList());
//数据推送
push(collect.toString().replace("[","").replace("]",""));
return collect;
}
private void push(String message) {
System.out.println(message);
WebSocket.sendInfoToAll(message);
}
}
还有一个html,看文章首页链接