在spring boot中使用WebSocket

pom

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>


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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

增加bean

import org.springframework.web.socket.server.standard.ServerEndpointExporter;

    /**
     * ServerEndpointExporter 作用
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

数据交互

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.websocket.WsSession;
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.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
// ws://localhost:8080/testserver/websocket/userId
public class WebSocketServer {

    /**
     *  与某个客户端的连接对话,需要通过它来给客户端发送消息
     */
    private Session session;
    /**
     * 标识当前连接客户端的用户Id
     */
    private String userId;

    /**
     *  用于存所有的连接服务的客户端,ConcurrentHashMap是线程安全的
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();


    /**
     *  解决socket无法注入bean的问题
     */
    private static XxxService xxxService;
    @Autowired
    public void setChatService(XxxService xxxService) {
        WebSocketServer.xxxService = xxxService;
    }

    /**
     *  socket连接建立
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId){
    	this.session = session;
        this.userId = userId;
        webSocketMap.put(userId, this);
		// do something code
    }

    @OnClose
    public void onClose(){
		// do something code
        webSocketMap.remove(userId);
    }

    @OnError
    public void onerror(Session session, Throwable throwable)
    {
		// do something code
        // webSocketMap.remove(userId);
        log.info("socket communicate exception.");
    }

    @OnMessage
    public void onMessage(Session session, String message){
    	JSONObject messageJson;
    	try {
    		messageJson = JSON.parseObject(message);
    	}catch(Exception e) {
    		return;
    	}

        String name = messageJson.getString("Id");
        Long Id = messageJson.getLong("Id");
		String userId = messageJson.getString("userId");

		// 业务查询 
		Object obj = XxxService.query(Id, name);

		JSONObject result = new JSONObject();
		result.put("msgId", "MsgInfo");
		result.put("msgContent", JSON.toJSON(obj));
		String resultString = result.toJSONString();
		
		// 发送
		appointSending(userId, resultString); 
		
		// 或直接发送
		// session.getBasicRemote().sendText(resultString)

    }

    /**
     * 指定发送
     * @param userId
     * @param message
     */
    public void appointSending(String userId, String message)
    {
        try {
            webSocketMap.get(userId).session.getBasicRemote().sendText(message);
        }catch (Exception e){
            log.error(String.format("fail to sendMessage, userId is %s", userId));
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值