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;
@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;
@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;
@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(); }
@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("给所有人"); } }
@OnError public void onError(Session session, Throwable error) { error.printStackTrace(); }
public void sendMessageTo(String message, String username) { for (WebSocket item : clients.values()) { if (item.username.equals(username)) { item.session.getAsyncRemote().sendText(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相关方法即可.