spring boot 使用websocket

依赖

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

配置

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

websocket服务端点

@ServerEndpoint("/ws/test/{username}")
@Component
public class TestEndpoint {

    static final Logger loggger = LoggerFactory.getLogger(TestEndpoint.class);
    private static int onlineCount = 0;
    // 用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap<String, TestEndpoint> webSocketMap = new ConcurrentHashMap<>();
    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    // 接收username
    private String username = "";

    // 发送自定义消息
    public static void sendInfo(String message, String username) {
        loggger.info("发送消息到:" + username + ",报文:" + message);
        if (StringUtils.isNotBlank(username) && webSocketMap.containsKey(username)) {
            try {
                webSocketMap.get(username).sendMessage(message);
            } catch (Exception e) {
                loggger.error(e.getMessage(), e);
            }
        } else {
            loggger.error("用户" + username + ",不在线!");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        TestEndpoint.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        TestEndpoint.onlineCount--;
    }

    // 打开连接
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        this.session = session;
        this.username = username;
        if (webSocketMap.containsKey(username)) {
            webSocketMap.remove(username);
            webSocketMap.put(username, this);
        } else {
            webSocketMap.put(username, this);
            addOnlineCount();
        }

        loggger.info("用户连接:" + username + ",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            loggger.error("用户:" + username + ",网络异常!!!!!!");
        }
    }

    // 关闭连接
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(username)) {
            webSocketMap.remove(username);
            subOnlineCount();
        }
        loggger.info("用户退出:" + username + ",当前在线人数为:" + getOnlineCount());
    }

    // 接收消息
    @OnMessage
    public void onMessage(String message, Session session) {
        loggger.info("用户消息:" + username + ",报文:" + message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        loggger.error("用户错误:" + this.username + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    // 推送消息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}

客户端

var webSocket = null;
if ('WebSocket' in window) {
    webSocket = new WebSocket('ws://serverhost/ws/test/username');
	// 接收消息
	webSocket.onmessage = function (event) {
	    // event.data;
	}	
	// 关闭连接
	webSocket.onclose = function () {
	}
	webSocket.onerror = function () {    
	}
	// 打开连接
	webSocket.onopen = function () {
		// 发送消息
	    var message = "msgfromclient";
	    webSocket.send(message);
	}
} else {
    alert('Not support websocket')
}

posted on 2020-07-08 16:58  路过君  阅读(87)  评论(0编辑  收藏  举报

导航