区别与好处
-
通信模式:
- HTTP 请求: HTTP 请求是基于请求-响应模型的。客户端发送请求到服务器,然后服务器处理请求并返回响应。每次请求都需要重新建立连接。
- WebSocket:WebSocket 是一个全双工协议,允许客户端和服务器之间进行持续的双向通信。一旦连接建立,数据可以在双方之间实时传输,而不需要每次都重新建立连接。
-
性能和效率:
- HTTP 请求:由于每次请求都需要重新建立连接和断开连接,存在较大的开销,特别是在高频率通信的情况下。
- WebSocket:只需一次握手即可建立持久连接,之后的数据传输效率更高,延迟更低,非常适合需要实时更新的应用场景,如在线聊天、实时游戏、股票行情等。
-
数据传输:
- HTTP 请求:每次请求和响应都包含完整的 HTTP 头信息,这增加了数据传输的开销。
- WebSocket:建立连接后,数据包的头信息非常小,极大地减少了数据传输的开销。
-
实时性:
- HTTP 请求:实现实时性通常需要频繁的轮询(Polling),这会增加服务器的负载。
- WebSocket:支持服务器主动推送消息给客户端,提供了真正的实时通信能力。
使用方法
Java 后端 WebSocket 实现
使用 Spring Boot 实现 WebSocket 服务:
-
依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId> </dependency>
-
配置 WebSocket:
import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(new MyWebSocketHandler(), "/websocket").setAllowedOrigins("*");} }
-
WebSocket 处理器:
import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import org.springframework.web.socket.TextMessage;public class MyWebSocketHandler extends TextWebSocketHandler {@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {String payload = message.getPayload();session.sendMessage(new TextMessage("Server received: " + payload));} }
Vue 前端 WebSocket 实现
-
创建 WebSocket 连接:
const socket = new WebSocket('ws://localhost:8080/websocket');socket.onopen = () => {console.log('WebSocket connection established');socket.send('Hello Server!'); };socket.onmessage = (event) => {console.log('Message from server: ', event.data); };socket.onerror = (error) => {console.log('WebSocket error: ', error); };socket.onclose = () => {console.log('WebSocket connection closed'); };
-
在 Vue 组件中使用:
<template><div><h1>WebSocket Example</h1><button @click="sendMessage">Send Message</button></div> </template><script> export default {data() {return {socket: null};},mounted() {this.socket = new WebSocket('ws://localhost:8080/websocket');this.socket.onmessage = (event) => {console.log('Message from server: ', event.data);};},methods: {sendMessage() {if (this.socket && this.socket.readyState === WebSocket.OPEN) {this.socket.send('Hello Server!');}}} }; </script>
好的,为了更好地理解这些代码,我会添加详细的注释。以下是带有注释的 Java 和 Vue WebSocket 实现示例:
使用
实时聊天
Java 后端 WebSocket 实现
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;import java.util.ArrayList;
import java.util.List;public class ChatWebSocketHandler extends TextWebSocketHandler {// 存储所有连接的 WebSocket 会话private List<WebSocketSession> sessions = new ArrayList<>();// 新的 WebSocket 连接建立后调用@Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {sessions.add(session); // 将新的会话添加到列表中}// 接收到消息时调用@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {// 向所有连接的会话广播消息for (WebSocketSession s : sessions) {if (s.isOpen()) {s.sendMessage(new TextMessage("User " + session.getId() + ": " + message.getPayload()));}}}
}
Vue 前端 WebSocket 实现
<template><div><h1>Chat Room</h1><input v-model="message" @keyup.enter="sendMessage" placeholder="Type a message"/><ul><li v-for="msg in messages" :key="msg">{{ msg }}</li></ul></div>
</template><script>
export default {data() {return {socket: null, // WebSocket 对象message: '', // 当前输入的消息messages: [] // 收到的消息列表};},mounted() {// 创建 WebSocket 连接this.socket = new WebSocket('ws://localhost:8080/chat');// 设置消息接收处理函数this.socket.onmessage = (event) => {this.messages.push(event.data); // 将收到的消息添加到列表中};},methods: {sendMessage() {// 发送消息到服务器if (this.message.trim() !== '') {this.socket.send(this.message);this.message = ''; // 清空输入框}}}
};
</script>
实时股票行情
Java 后端 WebSocket 实现
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;
import java.util.Timer;
import java.util.TimerTask;public class StockPriceWebSocketHandler extends TextWebSocketHandler {// 存储所有连接的 WebSocket 会话private List<WebSocketSession> sessions = new ArrayList<>();// 新的 WebSocket 连接建立后调用@Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {sessions.add(session); // 将新的会话添加到列表中startSendingStockPrices(session); // 开始发送股票价格}// 定时向客户端发送股票价格private void startSendingStockPrices(WebSocketSession session) {Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {try {double stockPrice = Math.random() * 1000; // 模拟股票价格session.sendMessage(new TextMessage("Stock Price: " + stockPrice));} catch (Exception e) {e.printStackTrace();}}}, 0, 1000); // 每秒更新一次}
}
Vue 前端 WebSocket 实现
<template><div><h1>Real-Time Stock Prices</h1><ul><li v-for="price in stockPrices" :key="price">{{ price }}</li></ul></div>
</template><script>
export default {data() {return {socket: null, // WebSocket 对象stockPrices: [] // 收到的股票价格列表};},mounted() {// 创建 WebSocket 连接this.socket = new WebSocket('ws://localhost:8080/stock');// 设置消息接收处理函数this.socket.onmessage = (event) => {this.stockPrices.push(event.data); // 将收到的股票价格添加到列表中if (this.stockPrices.length > 10) {this.stockPrices.shift(); // 保留最新的 10 条记录}};}
};
</script>