WebSocket 和 HTTP 请求区别

区别与好处

  1. 通信模式

    • HTTP 请求: HTTP 请求是基于请求-响应模型的。客户端发送请求到服务器,然后服务器处理请求并返回响应。每次请求都需要重新建立连接。
    • WebSocket:WebSocket 是一个全双工协议,允许客户端和服务器之间进行持续的双向通信。一旦连接建立,数据可以在双方之间实时传输,而不需要每次都重新建立连接。
  2. 性能和效率

    • HTTP 请求:由于每次请求都需要重新建立连接和断开连接,存在较大的开销,特别是在高频率通信的情况下。
    • WebSocket:只需一次握手即可建立持久连接,之后的数据传输效率更高,延迟更低,非常适合需要实时更新的应用场景,如在线聊天、实时游戏、股票行情等。
  3. 数据传输

    • HTTP 请求:每次请求和响应都包含完整的 HTTP 头信息,这增加了数据传输的开销。
    • WebSocket:建立连接后,数据包的头信息非常小,极大地减少了数据传输的开销。
  4. 实时性

    • HTTP 请求:实现实时性通常需要频繁的轮询(Polling),这会增加服务器的负载。
    • WebSocket:支持服务器主动推送消息给客户端,提供了真正的实时通信能力。

使用方法

Java 后端 WebSocket 实现

使用 Spring Boot 实现 WebSocket 服务:

  1. 依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    
  2. 配置 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 {
    
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new MyWebSocketHandler(), "/websocket").setAllowedOrigins("*");
        }
    }
    
  3. 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 {
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            String payload = message.getPayload();
            session.sendMessage(new TextMessage("Server received: " + payload));
        }
    }
    

Vue 前端 WebSocket 实现

  1. 创建 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');
    };
    
  2. 在 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 后端 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 连接建立后调用
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session); // 将新的会话添加到列表中
    }

    // 接收到消息时调用
    @Override
    protected 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 连接建立后调用
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session); // 将新的会话添加到列表中
        startSendingStockPrices(session); // 开始发送股票价格
    }

    // 定时向客户端发送股票价格
    private void startSendingStockPrices(WebSocketSession session) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

懒人w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值