Springboot+WebSocket实现一对一聊天和公告的示例代码

网友投稿 290 2022-10-27


Springboot+WebSocket实现一对一聊天和公告的示例代码

1.POM文件导入Springboot整合websocket的依赖

org.springframework.boot

spring-boot-starter-websocket

2.1.6.RELEASE

2.注册WebSocket的Bean交给Spring容器管理

@Configuration

public class WebSocketServiceConfig {

@Bean

public ServerEndpointExporter serverEndpointExporter() {

return new ServerEndpointExporter();

}

}

3.WebSocket服务端实现

@ServerEndpoint 注解声明为一个WebSocket服务,访问地址为/chat/{username},@Component将其注册为Spring的一个组件,交给Spring进行管理

@ServerEndpoint("/chat/{username}")

@Component

@Slf4j

public class WebSocket {

//注入dao或者service,注意:因为dao层接口和service层都是单例的Bean

//webSocket 不是单例的,所以在注入dao或者service时,需要用set方法对其进行注入,保证每一个都是独立的

private static ChatMapper chatMapper;

//参数中的ChatMapper 是 单例池中的ChatMapper

@Autowired

public void setChatMapper(ChatMapper chatMapperBean){

WebSocket.chatMapper = chatMapperBean;

}

//当前连接数

private static int onLinePersonNum;

//定义为Map结构,key值代表用户名称或其他唯一标识,Value代表对应的WebSocket连接。

//ConcurrentHashMap 保证线程安全,用来存放每个客户端对应的WebSocket对象

private static Map webSocketMap = new ConcurrentHashMap();

//用户名

private String username;

//当前httpSession

private Session session;

/**

* 打开链接

* @param username

* @param session

*/

@OnOpen

public void openConnect(@PathParam("username")String username, Session session){

this.session = session;

this.username = username;

//在线连接数+1

onlinePerNumAdd();

//用户名和当前用户WebSocket对象放进Map中

webSocketMap.put(this.username,this);

log.info("{}连接服务器成功。。。。",this.username);

}

/**

* 关闭连接

* @param username

* @param session

* @PathParhttp://am 用来获取路径中的动态参数Key值

*/

@OnClose

public void closeConnect(@PathParam("username")String username, Session session){

webSocketMap.remove(username);

//在线连接数-1

onlinePerNumSub();

log.info("{} 断开连接。。。",username);

}

/**

* 错误提示

*/

@OnError

public void errorConnect(Session session, Throwable error){

log.error("websocket连接异常:{}",error.getMessage());

}

@OnMessage

public void send(String message, Session session) throws IOException {

ObjectMapper objectMapper = new ObjectMapper();

Map map = objectMapper.readValue(message, Map.class);

sendMessage(map.get("username").toString(),message);

}

/**

* 点对点发送

* @param username

* @param message

* @throws IOException

*/

private void sendMessage(String username,String message) throws IOException {

WebSocket webSocket = webSocketMap.get(username);

webSocket.session.getBasicRemote().sendText(message);

}

/**

* 广播类型发送

* @param message

* @throws IOException

*/

private void sendMessage(String message) throws IOException {

Set keys = webSocketMap.keySet();

for (String key : keys) {

WebSocket webSocket = webSocketMap.get(key);

webSocket.sendMessage(message);

}

}

private synchronized static void onlinePerNumAdd(){

WebSocket.onLinePersonNum ++;

}

private synchronized static void onlinePerNumSub(){

WebSocket.onLinePersonNum --;

}

private synchronized static int getOnLinePerNum(){

return WebSocket.onLinePersonNum;

}

}

4.webSocket客户端

chat1.html


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:老男孩35期决心书
下一篇:案例 同城双核心机房的专线接入方式
相关文章

 发表评论

暂时没有评论,来抢沙发吧~