SpringBoot 使用 WebSocket 非常方便,依赖上仅需要添加相应的 Starter 即可。
1.添加 starter 依赖
在maven中添加引用
<!--websocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>1.3.5.RELEASE</version> </dependency>
2.添加websocket配置
package com.ckfuture.springcloud.config; 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(); } }
3.通信处理类
package com.ckfuture.springcloud.config; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; @ServerEndpoint(value = "/websocket") @Component public class MyWebSocket { private static int onlineCount = 0; private static CopyOnWriteArraySet<MyWebSocket> websocketSet = new CopyOnWriteArraySet<MyWebSocket>(); private Session session; /** * 连接建立成功调用的方法 * @param session */ @OnOpen public void onOpen(Session session){ this.session = session; websocketSet.add(this); addOnlineCount(); System.out.println("有新连接加入!当前在线人数为:"+getOnlineCount()); try{ sendMessage("8888"); }catch (IOException e){ System.out.println("IO异常"); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose(){ websocketSet.remove(this); subOnlineCount(); System.out.println("有一连接关闭!当前在线人数为:"+getOnlineCount()); } /** * 收到客户端消息后调用的方法 * @param message * @param session */ @OnMessage public void onMessage(String message,Session session){ System.out.println("来自客户端的消息:"+message); for(MyWebSocket item : websocketSet){ try{ item.sendMessage(message); }catch (IOException e){ e.printStackTrace(); } } } /** * 发生错误时候调用的方法 * @param session * @param error */ @OnError public void one rror(Session session,Throwable error){ System.out.println("发生错误"); error.printStackTrace(); } /** * 发送消息方法 * @param message 消息内容 * @throws IOException */ public void sendMessage(String message) throws IOException{ this.session.getBasicRemote().sendText(message); } public static void sendInfo(String message) throws IOException{ for(MyWebSocket item : websocketSet){ try{ item.sendMessage(message); }catch (IOException e){ continue; } } } public static synchronized int getOnlineCount(){ return onlineCount; } public static synchronized void addOnlineCount(){ MyWebSocket.onlineCount++; } public static synchronized void subOnlineCount(){ MyWebSocket.onlineCount--; } }
4.启动程序,利用在线测试工具测试
本文引用:https://blog.csdn.net/qq_40618664/article/details/118016408
标签:websocket,springboot,void,session,import,message,public From: https://www.cnblogs.com/ckfuture/p/16857683.html