1、引入依赖:
compile "org.springframework.boot:spring-boot-starter-web:${verSpringBoot}"
compile "org.springframework.boot:spring-boot-starter-websocket:${verSpringBoot}"
2、添加Webscoket配置:
/** * ServerEndpointExporter 作用 * * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint * * @return */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }
3、后端代码:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; @Component @ServerEndpoint("/websocket/{id}") public class WebSocketServer { public Logger log = LoggerFactory.getLogger(getClass()); /** * 客户端ID */ private String id = ""; /** * 与某个客户端的连接会话,需要通过它来给客户端发送数据 */ private Session session; /** * 记录当前在线连接数(为保证线程安全,须对使用此变量的方法加lock或synchronized) */ private static int onlineCount = 0; /** * 用来存储当前在线的客户端(此map线程安全) */ private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>(); /** * 连接建立成功后调用 */ @OnOpen public void onOpen(@PathParam(value = "id") String id, Session session) { this.session = session; // 接收到发送消息的客户端编号 this.id = id; // 加入map中 webSocketMap.put(id, this); // 在线数加1 addOnlineCount(); log.info("客户端" + id + "加入,当前在线数为:" + getOnlineCount()); try { sendMessage("WebSocket连接成功"); } catch (IOException e) { log.error("WebSocket IO异常"); } } /** * 连接关闭时调用 */ @OnClose public void onClose() { // 从map中删除 webSocketMap.remove(this.id); // 在线数减1 subOnlineCount(); log.info("有一连接关闭,当前在线数为:" + getOnlineCount()); } /** * 收到客户端消息后调用 * @param message 客户端发送过来的消息<br/> * 消息格式:内容 - 表示群发,内容|X - 表示发给id为X的客户端 * @param session 用户信息 */ @OnMessage public void onMessage(String message, Session session) { log.info("来自客户端的消息:" + message); String[] messages = message.split("[|]"); try { if (messages.length > 1) { sendToUser(messages[0], messages[1]); } else { sendToAll(messages[0]); } } catch (IOException e) { log.error(e.getMessage(), e); } } /** * 发生错误时回调 * * @param session 用户信息 * @param error 错误 */ @OnError public void onError(Session session, Throwable error) { log.error("WebSocket发生错误"); error.printStackTrace(); } /** * 推送信息给指定ID客户端,如客户端不在线,则返回不在线信息给自己 * * @param message 客户端发来的消息 * @param sendClientId 客户端ID */ public void sendToUser(String message, String sendClientId) throws IOException { if (webSocketMap.get(sendClientId) != null) { if (!id.equals(sendClientId)) { webSocketMap.get(sendClientId) .sendMessage("客户端" + id + "发来消息:" + " <br/> " + message); } else { webSocketMap.get(sendClientId).sendMessage(message); } } else { // 如客户端不在线,则返回不在线信息给自己 sendToUser("当前客户端不在线", id); } } public static void sendToWeb(String message, String sendClientId) throws IOException { if (webSocketMap.get(sendClientId) != null) { webSocketMap.get(sendClientId).sendMessage(message); } else { // 如客户端不在线,则返回不在线信息给自己 System.out.println(sendClientId + "=当前客户端不在线"); } } /** * 群送发送信息给所有人 * * @param message 要发送的消息 */ public void sendToAll(String message) throws IOException { for (String key : webSocketMap.keySet()) { webSocketMap.get(key).sendMessage(message); } } /** * 发送消息 * @param message 要发送的消息 */ private void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 获取在线人数 * @return 在线人数 */ private static synchronized int getOnlineCount() { return onlineCount; } /** * 有人上线时在线人数加一 */ private static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } /** * 有人下线时在线人数减一 */ private static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }
4、前端代码:
<!DOCTYPE HTML> <html> <head> <title>My WebSocket</title> </head> <body> <input id="text" type="text" /> <button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; //判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址 if ('WebSocket' in window) { websocket = new WebSocket("ws://127.0.0.1:16666/ts/websocket/1"); } else { alert('Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function() { setMessageInnerHTML("error"); }; //连接成功建立的回调方法 websocket.onopen = function(event) { setMessageInnerHTML("open"); } //接收到消息的回调方法 websocket.onmessage = function(event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function() { setMessageInnerHTML("close"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function() { websocket.close(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script> </html>
5、测试代码:
@RequestMapping(value="/sendMessage/{clientId}",method = {RequestMethod.GET}) public void sendTest(@PathVariable String clientId) throws Throwable{ WebSocketServer.sendToWeb("你有一个新任务"+System.currentTimeMillis(), clientId); }