ubuntu 之 lftp 上傳 和下載
阿新 • • 發佈:2021-08-04
websocket 是一種在單個TCP連線上進行全雙工通訊的協議 HTTP請求可能包含較長的頭部,其中真正有效的資料可能只是很小的一部分,顯然這樣會浪費很多的頻寬等資源 https://www.cnblogs.com/xuwenjin/p/12664650.html <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <!-- websocket --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } @Slf4j @Component @ServerEndpoint(value="/websocketTest/{userId}") public class WebsocketTest { private static String userId; //連線時執行 @OnOpen public void onOpen(@PathParam("userId") String userId, Session session) throws IOException { this.userId = userId; log.info("新連線:{}",userId); } //關閉時執行 @OnClose public void onClose(){ log.info("連線:{} 關閉",this.userId); } //收到訊息時執行 @OnMessage public void onMessage(String message, Session session) throws IOException { log.info("收到使用者{}的訊息{}",this.userId,message); session.getBasicRemote().sendText("收到"+this.userId+"的訊息:"+message); //回覆使用者 log.info("wait before"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("wait ater"); session.getBasicRemote().sendText("收到"+this.userId+"的訊息2:"+message); //回覆使用者 } //連線錯誤時執行 @OnError public void onError(Session session, Throwable error){ log.info("使用者id為:{}的連線傳送錯誤",this.userId); error.printStackTrace(); } } <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> websocket Demo---- user000 <br /> <input id="text" type="text" /> <button onclick="send()"> Send </button> <button onclick="closeWebSocket()"> Close </button> <div id="message"> </div> <script type="text/javascript"> //判斷當前瀏覽器是否支援WebSocket if('WebSocket' in window){ websocket = new WebSocket("ws://localhost:9990/websocketTest/userIdValue001"); console.log("link success") }else{ alert('Not support websocket') } //連線發生錯誤的回撥方法 websocket.onerror = function(){ setMessageInnerHTML("error"); }; //連線成功建立的回撥方法 websocket.onopen = function(event){ setMessageInnerHTML("open"); } console.log("-----") //接收到訊息的回撥方法 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> </body> </html>