用到的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
java服务端代码
springboot配置
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
WebSocket服务
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {
private static AtomicInteger onlineCount = new AtomicInteger(0);
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
private Session session;
private String sid = "";
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
System.out.println(session.getRequestURI());
log.info("有新用户登录:" + sid + ", 当前在线人数为" + getOnlineCount());
this.sid = sid;
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
log.info("有一用户连接关闭!当前在线人数为" + getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口" + sid + "的信息:" + message);
for (WebSocketServer item : webSocketSet) {
item.sendMessage("欢迎客户登录");
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) {
try {
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("消息推送失败");
e.printStackTrace();
}
}
public static void pushMessageToAllUser(String message){
for (WebSocketServer item : webSocketSet) {
item.sendMessage(message);
}
}
public static void sendInfo(String message, String sid) {
log.info("推送消息到窗口" + sid + ",推送内容:" + message);
for (WebSocketServer item : webSocketSet) {
if(item.sid.equals(sid)){
item.sendMessage(message);
}
}
}
public static int getOnlineCount() {
return onlineCount.get();
}
public static void addOnlineCount() {
WebSocketServer.onlineCount.addAndGet(1);
}
public static void subOnlineCount() {
WebSocketServer.onlineCount.decrementAndGet();
}
}
前端代码
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
socket = new WebSocket("ws://localhost:8080/websocket/" + 55);
socket.onopen = function() {
console.log("Socket 已打开");
socket.send("这是来自客户端的消息" + location.href + new Date());
};
socket.onmessage = function(msg) {
console.log(msg.data);
alert(msg.data)
};
socket.onclose = function() {
console.log("Socket已关闭");
};
socket.onerror = function() {
alert("Socket发生了错误");
}
}