springboot使用websocket

1.引入websocket依赖

<dependency>    
	<groupId>org.springframework.boot</groupId>    
	<artifactId>spring-boot-starter-websocket</artifactId>    
	<version>2.7.12</version>
</dependency>

2.创建配置类

@Configuration
@EnableWebSocket
public class WebSocketConfig {
    @Bean    
	public ServerEndpointExporter serverEndpointExporter(){
    	return new ServerEndpointExporter();    
	}
}

3.创建websocket类

@Component
@ServerEndpoint("/websocket/{userId}")
@Slf4j
public class WebSocket {

    private Session session;    
	private static Map<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();    
	private static List<Session> sessionList = new LinkedList<>(); 
	   
/**     
* 客户端发起websocket连接请求成功建立连接时触发     
* @param session 
* @param userId     
* */    
@OnOpen    
public void onOpen(Session session, @PathParam("userId") String userId) {
	this.session = session;
	this.webSocketMap.put(userId, this);        
	sessionList.add(session); 
	log.info("【websocket消息】有新的连接用户{}, 总数:{}",userId, webSocketMap.size());    
}

/**
*客户端关闭时websocket连接时触发     
*/
@OnClose    
public void onClose(@PathParam("userId") String userId) throws IOException {
	session.close();
	this.webSocketMap.remove(userId);   
	log.info("【websocket消息】连接断开, 总数:{}", webSocketMap.size());    
}

/**     
* 客户端向服务端发送消息时触发     
* @param session     
* @param message     
* @throws IOException     
* */    
@OnMessage    
public void onMessage(Session session,  String message) throws IOException {
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();        
        String userId = requestParameterMap.get("userId").get(0);
        log.info("【websocket消息】收到客户端发来的消息:{}", message);        
        if (message.startsWith("hello")) {
            session.getBasicRemote().sendText(userId+"信息收到" + message.replace("hello", ""));        
        }
        sessionList.forEach(s->{
		try {     
			s.getBasicRemote().sendText(message);  
		} catch (IOException e) {
			throw new RuntimeException(e);            
		}
		});    
	}
}
连接地址:
ws://localhost:(springboot程序的端口号)/{userId} (视个人情况而定)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值