package socketTest; import java.util.Set; import javax.websocket.Endpoint; import javax.websocket.server.ServerApplicationConfig; import javax.websocket.server.ServerEndpointConfig; /** * 1, webSocket 的配置類, 需要實現接口 ServerApplicationConfig * 2, webSocket 類在掃描到之后根據需要在實現的方法中進行一定的過濾, 返回過濾后的才能被前端訪問 * 3, getAnnotatedEndpointClasses 基於注解的 webSocket 掃描方法 * 4, getEndpointConfigs 基於 XML 配置文件的的 webSocket 掃描方法 */ public class MyWbeSocketConfig implements ServerApplicationConfig { public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> webSockets) { return webSockets; } public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> arg0) { return null; } }
package socketTest; import java.io.IOException; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** * 1, WebSocket可以通過注解的方式聲明 @ServerEndpoint("/WebSocket") * 2, 添加注解之后需要在配置文件中返回, 在配置文件中可以過濾 * 3, WebSocket 和 Servlet 相同都是多列的, 不會互相干擾 * 4, WebSocket 請求時訪問 open 方法, 可以用注解 @OnOpen 標明 * 5, WebSocket 關閉時訪問 close 方法, 可以用注解 @OnClose 表名 */ @ServerEndpoint("/WebSocket") public class WebSocketDemo { @OnOpen public void open(Session session) { String id = session.getId(); System.out.println("通道 " + id + " 打開"); } @OnClose public void close (Session session) { String id = session.getId(); try { session.getBasicRemote().sendText("客戶端" + id + "關閉成功"); } catch (IOException e) { System.out.println("客戶端" + id + "關閉失敗"); } } @OnMessage public void message(Session session, String msg) { String outMessade = "客戶端 " + session.getId() + " 說:" + msg; System.out.println(outMessade); String returnMessage = "你剛才說:" + msg; try { session.getBasicRemote().sendText(returnMessage); } catch (IOException e) { System.out.println("返回數據失敗"); } } }
//html代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>WebSocket</title> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <input id="CreateSocket" type="button" value="創建WebSocKet" /> <input id="Message" type="text" value=""/> <input id="Send" type="button" value="發送" /> <input id="Close" type="button" value="關閉WebSocket" /> </body> <script type="text/javascript"> /** * 創建 WebSocKet 的方法 */ function createWebSocket(urlValue){ if("WebSocket" in window){ return new WebSocket(urlValue); } if ("MozWebSocket" in window){ return new MozWebSocket(urlValue); } console.log("瀏覽器不支持 WebSocKet"); } /** * 1, 創建WebSocket * 2, WebScoket 的地址為ws協議 */ var webSocket = null; var urlValue = "ws://localhost:8080/socket/WebSocket"; $('#CreateSocket').on('click', function(){ webSocket = createWebSocket(urlValue); // 服務器返回數據時執行 webSocket.onmessage = function(msg){ console.log(msg.data); } // 請求關閉時執行 webSocket.onclose = function(){ console.log(arguments); } }); $('#Send').on('click', function(){ console.log("進入發送--------") var message = $('#Message').val().trim(); console.log("進入發送內容--------"+message); if(message == ""){ console.error("發送的內容不能為空!"); return; } if(webSocket == null){ console.log("未創建 WebSocket 請求!"); return; } // 向服務器發送請求的方法 webSocket.send(message); console.log("message=============="+message); $('#Message').val(""); }); $('#Close').on('click', function(){ // 請求關閉時執行 webSocket.onclose = function(){ console.log(arguments); } }); </script>
pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cn</groupId> <artifactId>socket</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> </dependency> </dependencies> </project>
//創建一個maven項目打war包
請求路徑