SpringBoot集成websocket(java注解⽅式)
第⼀种:SpringBoot官⽹提供了⼀种websocket的集成⽅式第⼆种:javax.websocket中提供了元注解的⽅式
下⾯讲解简单的第⼆种
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!-- 打包成war包这个⼀定要设置为provided,不然websocket连不上 -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类
WebSocketConfig.java
fig;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @description: WebSocketConfig类
* @author: Wzq
* @create: 2020-04-15 11:22
*/
//当我们使⽤外部Tomcat时,项⽬的管理权将会由Spring交接⾄Tomcat。
// ⽽Tomcat7及后续版本是对websocket直接⽀持的,且我们所使⽤的jar包也是tomcat提供的。
// 但是我们在WebSocketConfig中将ServerEndpointExporter指定给Spring管理。
// ⽽部署后ServerEndpoint是需要Tomcat直接管理才能⽣效的。
// 所以此时即就是此包的管理权交接失败,那肯定不能成功了。
// 最后我们需要将WebSocketConfig中的bean配置注释掉
@Configuration
public class WebSocketConfig {
// 本地开发打开注释,打包成war注释掉再打包
/
/ @Bean
// public ServerEndpointExporter serverEndpointExporter() {
// return new ServerEndpointExporter();
// }
}
MeetingWebSocket.java
ller;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
llect.Lists;
llect.Maps;
stants.Constants;
framework.util.JsonUtils;
trainsys.user.service.UserMessageService;
trainsys.user.view.MeetingEmployeeChatListView;
trainsys.user.view.UserMessageListView;
stants.SocketConstants;
del.MeetingSocketModel;
trainsys.websocket.view.MeetingSocketView;
java.Log;
log4j.Log4j2;
slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import urrent.ConcurrentHashMap;
/**
* @description:
* @author: Wzq
* @create: 2020-04-15 11:30
*/
@Component
@ServerEndpoint("/websocket/{meetingId}/{empId}")
@Log
public class MeetingWebSocket {
private static UserMessageService userMessageService;
@Autowired
public void setUserMessageService(UserMessageService userMessageService){
MeetingWebSocket.userMessageService = userMessageService;
}
// concurrent包的线程安全Map,⽤来存放每个客户端对应的MyWebSocket对象。 Long为会议室id
private static ConcurrentHashMap<String,MeetingWebSocket> webSocketMap = new ConcurrentHashMap<String,MeetingWebSocket>(); //会议id
private Long meetingId;
//当前⽤户id
private Long userId;
// 当前聊天对象Session
private Session session;
// 未读数量
private Integer notReadNum;
/**
* 连接建⽴成功调⽤的⽅法*/
@OnOpen
public void onOpen(Session session, @PathParam("meetingId") Long meetingId,@PathParam("empId") Long empId) {
log.info("onOpen->meetingId:" + meetingId);
//创建⼀个会议webSocket
this.session = session;
this.userId = empId;
webSocketMap.put(meetingId + "-" + userId,this);
}
/**
* 连接关闭调⽤的⽅法
*/
@OnClose
public void onClose() {
log.info("onClose!");
//那个关闭了连接清空map
ingId != null && this.userId != null){
String keyStr = ingId + "-" + this.userId;
}
}
/**
* 收到客户端消息后调⽤的⽅法
* @param message
*/
@OnMessage
public void onMessage(String message, Session session, @PathParam("meetingId") Long meetingId,@PathParam("empId") Long empId){ log.info("onMessage!" + message);
//发送消息给指定的⼈
this.sendMessageByUserId(MeetingId(),TargetEmpId());
}
/**
* 发⽣错误时调⽤
*/
@OnError
public void onError(Session session, Throwable error){
log.info("webSocket发⽣错误!");
error.printStackTrace();
}
spring framework/**
* 根据会议id和⽤户id获取Socket
* @param meetingId
* @param userId
*/
public static MeetingWebSocket getSocketByMeetingAndUserId(Long meetingId,Long userId){
for (String keyStr : webSocketMap.keySet()) {
String[] splitStr = keyStr.split("-");
String keyMeetingIdStr = splitStr[0];
String().equals(keyMeetingIdStr)){
(keyStr).userId.equals(userId)){
MeetingWebSocket meetingWebSocket = (keyStr);
return meetingWebSocket;
}
}
}
return null;
}
/**
* 根据会议和⽤户id发送消息
* @param msg
* @param meetingId
* @param userId
*/
private void sendMessageByUserId(String msg,Long meetingId,Long userId){
for (String keyStr : webSocketMap.keySet()) {
String[] splitStr = keyStr.split("-");
String keyMeetingIdStr = splitStr[0];
String().equals(keyMeetingIdStr)){
(keyStr).userId.equals(userId)){
MeetingWebSocket meetingWebSocket = (keyStr);
meetingWebSocket.sendMessage(msg);
}
}
}
}
/**
* 发送消息
* @param msg
*/
private void sendMessage(String msg){
try {
BasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试连接
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论