時間:2023-07-03 01:09:01 | 來源:網(wǎng)站運營
時間:2023-07-03 01:09:01 來源:網(wǎng)站運營
初識WebSocket協(xié)議:The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment to a remote host that has opted-in to communications from that code. The security model used for this is the origin-based security model commonly used by web browsers. The protocol consists of an opening handshake followed by basic message framing, layered over TCP. The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections.大意是說WebSocket是一個基于TCP協(xié)議的全雙工的應用層協(xié)議,主要用于Web瀏覽器,其目的是使基于瀏覽器、需要全雙工通信的web應用不再依賴于多個HTTP連接。
<!DOCTYPE html><html><head> <title>Testing websockets</title></head><body><div> <input type="submit" value="Start" onclick="start()" /></div><div id="messages"></div><script type="text/javascript"> var webSocket = new WebSocket('ws://139.129.95.147/TestWebSocket/websocket'); webSocket.onerror = function(event) { onError(event) }; webSocket.onopen = function(event) { onOpen(event) }; webSocket.onmessage = function(event) { onMessage(event) }; function onMessage(event) { document.getElementById('messages').innerHTML += '<br />' + event.data; } function onOpen(event) { document.getElementById('messages').innerHTML = 'Connection established'; } function onError(event) { alert(event.data); } function start() { webSocket.send('hello'); return false; }</script></body></html>
后端: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;@ServerEndpoint("/websocket")public class TestWebSocket { @OnMessage public void onMessage(String message, Session session) throws IOException, InterruptedException { // Print the client message for testing purposes System.out.println("Received: " + message); // Send the first message to the client session.getBasicRemote().sendText("This is the first server message"); // Send 3 messages to the client every 5 seconds int sentMessages = 0; while(sentMessages < 3){ Thread.sleep(5000); session.getBasicRemote(). sendText("This is an intermediate server message. Count: " + sentMessages); sentMessages++; } // Send a final message to the client session.getBasicRemote().sendText("This is the last server message"); } @OnOpen public void onOpen() { System.out.println("Client connected"); } @OnClose public void onClose() { System.out.println("Connection closed"); }}
在Tomcat中使用WebSocket,首先需要在服務器端建立一個endpoint,語法為@ServerEndpoint("/websocket")
然后在前端根據(jù)這個endpoint的url獲取一個WebSocket對象,然后調(diào)用其相關(guān)方法即可。由于代碼較為簡單,在本文中不在贅述,我會在后續(xù)文章中詳細分析。關(guān)鍵詞:協(xié)議
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。