一、 WebSocket简介
什么是WebSocket?
WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。
为什么需要 WebSocket?
1)因为 HTTP 协议有一个缺陷:通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。
2)效率,节约带宽。不停地轮询服务端数据这种方式,使用的是http协议,head信息很大,有效数据占比低, 而使用WebSocket方式,头信息很小,有效数据占比高。
二、 WebSocket简单实现
使用websocket前端有两种方式:
- 使用h5的标准
- 使用sockjs
使用Html5标准自然更方便简单,所以记录的是配合h5的使用方法。使用Html5标准自然更方便简单,所以本文记录的是配合h5的使用方法。
2.1 pom中引用websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.3 添加WebSocketHandler
实现TextWebSocketHandler接口
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
session.sendMessage(new TextMessage("Hello Client"));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
System.out.println("Get message from client: " + message.getPayload());
session.sendMessage(new TextMessage("received: " + message.getPayload()));
}
}
2.3 添加WebSocketConfig
添加Configuration和EnableWebSocket注解,并注册刚才添加的handler,注意 /websocket:需和前端保持路径一致
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/websocket");
}
}
2.4 添加index.html文件
位置在src/resouces/static
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
<script type="text/javascript">
var socket;
if(typeof(WebSocket) == "undefined") {
alert("您的浏览器不支持WebSocket");
}else{
socket = new WebSocket('ws://127.0.0.1:8080/websocket');
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("Socket发生了错误");
}
//获得消息事件
socket.onmessage = function(msg) {
console.log("获得消息事件"+msg.data);
};
}
function send() {
var txt= document.getElementById("msg").value;
socket.send(txt);
}
</script>
<input type="text" id="msg" value="please type the content here....">
<button onclick="send()">Send</button>
2.5 见证效果
访问:http://127.0.0.1:8080/index.html,注意因为我们使用IP作为socket地址,因此我们同样需要访问IP而不能用localhost。
Socket 已打开:Socket onopen 事件
获得消息事件Hello Client: 后端代码中建立socket连接之后,就推送消息Hello Client给前端。获得消息事件
同样当我们停止后台服务一样可以看到 Socket 已关闭
点击button向后端发送消息。
Github代码地址:https://github.com/PayneYu/spring-boot-study/tree/master/springboot-websocket