目录
前言
对websocket进行简单的应用
一、websocket工具类
示例:
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @Author: liury
* @Description: webSocket
* @DateTime: 2022/6/19 20:54
**/
@Slf4j
@Component
@ServerEndpoint("/webSocket")
public class WebSocket {
private static int onlineCount = 0;
private static CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<Session>();
private Session session;
private String username;
@OnOpen
public void onOpen( Session session) throws IOException {
this.session = session;
// this.username = userId;
addOnlineCount();
sessions.add(session);
log.info("已连接--------------: "+session);
}
@OnClose
public void onClose(Session session) throws IOException {
sessions.remove(session);
subOnlineCount();
log.info("关闭连接--------------: "+session);
}
@OnMessage
public void onMessage(String message) throws IOException {
sendMessageAll("给所有人");
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
for (Session session : sessions) {
log.info("--------------------------------------------------webSocket发送消息{}:" + System.currentTimeMillis(), To);
session.getAsyncRemote().sendText(message);
}
}
public static void sendMessageAll(String message) throws IOException {
if (sessions.size() != 0) {
for (Session s : sessions) {
if (s != null) {
s.getAsyncRemote().sendText(message);
}
}
}
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
}
二、遇到的问题:
1.开启websocket支持
代码如下(示例):
package com.yzd.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Author: liury
* @Description: 开启webSocket支持
* @DateTime: 2022/6/18 17:02
**/
@Configuration
public class WebSocketConfig {
/**
* 服务器节点
*
* 如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.注意
(示例):
注意http 用的是 ws ,https用的是wss
3.引用示例:
(示例):
//WebSocket发送消息给前端
ArrayList<Object> wsList = new ArrayList<>();
wsList.add(eventAddREQ);
String s = JSONObject.toJSONString(wsList);
try {
WebSocket.sendMessageAll(s);
} catch (IOException e) {
e.printStackTrace();
}
总结:
学习笔记在此记录
版权声明:本文为LRY98原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。