使用WebSocket笔记

SpringBoot下使用WebSocket笔记

引入Maven

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

准备好WebSocket配置类,提供WebSocket出口商Bean.(没有提供将连接不到端点)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
* @Author: HeTongHao
* @Date: 2019-06-03 18:17
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

定义一个端点

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* @Author: HeTongHao
* @Date: 2019-06-03 17:20
*/
@Slf4j
@Component
@ServerEndpoint("/webSocket/homeEvent/{username}")
public class WebSocket {
private static int onlineCount = 0;
private static Map<String, WebSocket> clients = new ConcurrentHashMap<>();
private Session session;
private String username;

/**
* 打开连接
*
* @param username
* @param session
*/
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) {
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
log.info("{},已连接", username);
}

/**
* 关闭连接回调
*/
@OnClose
public void onClose() {
clients.remove(username);
subOnlineCount();
}

/**
* 接收消息入口
*
* @param message
*/
@OnMessage
public void onMessage(String message) {
JSONObject jsonTo = JSONObject.parseObject(message);
String mes = (String) jsonTo.get("message");
if (!jsonTo.get("To").equals("All")) {
sendMessageTo(mes, jsonTo.get("To").toString());
} else {
sendMessageAll("给所有人");
}
}

/**
* 异常回调
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}

/**
* 发送消息给某个客户端
*
* @param message
* @param username
*/
public void sendMessageTo(String message, String username) {
// session.getBasicRemote().sendText(message);
for (WebSocket item : clients.values()) {
if (item.username.equals(username)) {
item.session.getAsyncRemote().sendText(message);
}
}
}

/**
* 发送消息给所有客户端
*
* @param message
*/
public void sendMessageAll(String message) {
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}

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

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

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

public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}

启动工程就可以通过 ws://127.0.0.1:8082/webSocket/homeEvent/xxx访问了

服务端如果要推送消息给客户端,注入这个端点,调用send相关方法即可.

在线模拟websocket请求工具

文章作者: 何同昊
文章链接: http://hetonghao.cn/2019/06/SpringBoot下使用WebSocket笔记/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 何同昊 Blog
支付宝超级火箭🚀
微信超级火箭🚀