时间:2023-07-03 01:09:01 | 来源:网站运营
时间:2023-07-03 01:09:01 来源:网站运营
初识WebSocket协议: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协议的全双工的应用层协议,主要用于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")
然后在前端根据这个endpoint的url获取一个WebSocket对象,然后调用其相关方法即可。由于代码较为简单,在本文中不在赘述,我会在后续文章中详细分析。关键词:协议