一、环境准备
- 开发工具:STS、HBuilderX
- JDK:1.8
- SpringBoot版本:2.2.2
二、后端搭建WebSocket服务
- 1.新建SpringBoot项目,并勾选WebSocket服务
- 2.项目目录结构如下
- 3.新建类文件WebSocket,文件位置如项目结构所示,代码编写如下
- 4.新建类文件WebSocketConfig,文件位置如项目结构所示,代码编写如下
1.新建SpringBoot项目,并勾选WebSocket服务
2.项目目录结构如下
3.新建类文件WebSocket,文件位置如项目结构所示,代码编写如下
package com.websocket.websocket;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.web.bind.annotation.RestController;
@ServerEndpoint("/WebSocket/{id}")
@RestController
public class WebSocket {
private static ConcurrentHashMap<String, WebSocket> webSocket = new ConcurrentHashMap<String, WebSocket>();
private String id;
private Session session;
@OnOpen
public void onOpen(Session session, @PathParam("id") String id) throws Exception {
this.id = id;
this.session = session;
webSocket.put(id, this);
sendMessageToId(this.id, "前端你好,我是后端,我正在通过WebSocket给你发送消息");
System.out.println(id + "接入连接");
}
@OnClose
public void onClose() {
webSocket.remove(this.id);
System.out.println(this.id + "关闭连接");
}
@OnMessage
public void onMessage(String message) {
System.out.println(this.id + "发来消息:" + message);
}
@OnError
public void onError(Throwable error) {
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public void sendMessageToId(String id, String message) throws IOException {
webSocket.get(id).sendMessage(message);
}
public void sendMessageToAll(String message) throws IOException {
for (String key : webSocket.keySet()) {
try {
webSocket.get(key).sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.新建类文件WebSocketConfig,文件位置如项目结构所示,代码编写如下
package com.websocket.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
三、新建前端项目
1.新建index.html文件,代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket</title>
</head>
<body>
</body>
<script type="text/javascript">
var websocket = null;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1:8080/WebSocket/zhongli");
} else {
alert('当前浏览器 Not support websocket')
}
websocket.onerror = function() {
console.log("WebSocket连接发生错误");
};
websocket.onopen = function() {
console.log("WebSocket连接成功");
}
websocket.onmessage = function(event) {
console.log(event.data);
}
websocket.onclose = function() {
console.log("WebSocket连接关闭");
}
function sendMsg(msg) {
websocket.send(msg);
}
</script>
</html>
四、项目演示
- 1.启动SpringBoot项目,项目正常启动
- 2.运行前端项目并查看控制台,浏览器控制台提示成功
- 3.检验后端是否正常给前端发送消息,查看浏览器控制台正常收到消息
- 4.检验前端是否正常给后端发送消息,浏览器控制台运行sendMsg()方法,正常给后端发送消息
1.启动SpringBoot项目,项目正常启动
2.运行前端项目并查看控制台,浏览器控制台提示成功
3.检验后端是否正常给前端发送消息,查看浏览器控制台正常收到消息
4.检验前端是否正常给后端发送消息,浏览器控制台运行sendMsg()方法,正常给后端发送消息
五、Github项目地址