WebSocket实时连接方案
后端
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类
package pers.os467.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
开启服务端websocket
定义webSocket客户端
package pers.os467.websocket;
import lombok.Data;
import javax.websocket.Session;
@Data
public class WebSocketClient {
//用户id
private String uid;
//webSocket会话
private Session session;
}
定义Websocket组件
下面是使用WebSocket实现的简单好友聊天功能
@Component
@ServerEndpoint(value = "/websocket/friend/{uid}", encoders = {JSONObjectEncoder.class})
public class FriendChatWebSocketServiceImpl implements FriendChatWebSocketService {
private static FriendSessionService friendSessionService;
@Autowired
public void setFriendSessionService(FriendSessionService friendSessionService){
this.friendSessionService = friendSessionService;
}
private ThreadLogger logger = ThreadLogger.getInstance();
//当前在线连接数
private static int onlineCount = 0;
//客户端表
private static ConcurrentHashMap<Integer, WebSocketClient> webSocketMap = new ConcurrentHashMap<>();
//当前连接客户端
private Session session;
//客户端用户id
private Integer uid;
@OnOpen
public void onOpen(Session session, @PathParam("uid") Integer uid){
if (!webSocketMap.containsKey(uid)){
addOnlineCount();
}
this.session = session;
this.uid = uid;
WebSocketClient client = new WebSocketClient();
client.setSession(session);
client.setUid(uid);
webSocketMap.put(uid,client);
logger.info("建立连接:"+uid + ",当前连接数:"+onlineCount);
}
@OnClose
public void onClose(){
if (webSocketMap.containsKey(uid)){
if (webSocketMap.size() > 0){
subOnlineCount();
}
webSocketMap.remove(uid);
}
logger.info("断开连接:"+uid + ",当前连接数:"+onlineCount);
}
@OnMessage
public void onMessage(String message,Session session){
JSONObject jsonObject = (JSONObject)JSON.parse(message);
String messageContext = (String) jsonObject.get("messageContext");
Integer fsId = (Integer) jsonObject.get("fsId");
Integer targetFriendUserId = (Integer) jsonObject.get("targetFriendUserId");
//发送消息
FriendMessageVo friendMessageVo = friendSessionService.sendUserMessage(messageContext, fsId, uid, targetFriendUserId);
//向好友推送
sendMessage(targetFriendUserId,friendMessageVo);
logger.info("接收到用户消息:"+uid+"报文"+messageContext);
}
@OnError
public void onError(Session session, Throwable throwable){
logger.error("用户错误:"+uid+",原因:"+throwable.getMessage());
throwable.printStackTrace();
}
public static void sendMessage(Integer uid,Object object){
try {
WebSocketClient webSocketClient = webSocketMap.get(uid);
if(webSocketClient!=null){
webSocketClient.getSession().getBasicRemote().sendObject(object);
}
} catch (IOException | EncodeException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
public static void sendMessage(String uid,String message){
WebSocketClient webSocketClient = webSocketMap.get(uid);
if (webSocketClient != null){
try {
webSocketClient.getSession().getBasicRemote().sendText(message);
} catch (IOException ioException) {
ioException.printStackTrace();
throw new RuntimeException(ioException.getMessage());
}
}
}
private synchronized void subOnlineCount() {
onlineCount--;
}
private synchronized void addOnlineCount() {
onlineCount++;
}
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件至 1300452403@qq.com