1.application.yml 配置文件
server:
port: 8080
spring:
thymeleaf:
prefix: classpath:/view/
suffix: .html
encoding: UTF-8
servlet:
content-type: text/html
# 生产环境设置true
cache: false
2.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.c3stones</groupId>
<artifactId>spring-boot-websocket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-websocket</name>
<description>Spring Boot WebSocket</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.核心类:配置类和服务类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocket配置类
*
* @author SW
*
*/
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter
* <p>
* 该Bean会自动注册添加@ServerEndpoint注解的WebSocket端点
* </p>
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* websocket 服务类
* @ServerEndpoint 这个注解有什么作用?
*
* 这个注解用于标识作用在类上,它的主要功能是把当前类标识成一个WebSocket的服务端
* 注解的值用户客户端连接访问的URL地址
*/
@Slf4j
@ServerEndpoint(value = "/webSocket/{sid}")
@Service
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static AtomicInteger onlineNum = new AtomicInteger();
//concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
//发送消息
public void sendMessage(Session session, String message) throws IOException {
if(session != null){
synchronized (session) {
session.getBasicRemote().sendText(message);
}
}
}
//给指定用户发送信息
public void sendInfo(String userName, String message){
Session session = sessionPools.get(userName);
try {
sendMessage(session, message);
}catch (Exception e){
e.printStackTrace();
}
}
//建立连接成功调用
@OnOpen
public void onOpen(Session session, @PathParam(value = "sid") String userName){
if(sessionPools.containsKey(userName)){
sessionPools.remove(userName);
sessionPools.put(userName,session);
//加入set中
}else{
sessionPools.put(userName, session);
//加入set中
addOnlineCount();
//在线数加1
}
sessionPools.put(userName, session);
addOnlineCount();
System.out.println(userName + "加入webSocket!当前人数为" + onlineNum);
try {
sendMessage(session, "欢迎" + userName + "加入连接!");
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接时调用
@OnClose
public void onClose(@PathParam(value = "sid") String userName){
sessionPools.remove(userName);
subOnlineCount();
System.out.println(userName + "断开webSocket连接!当前人数为" + onlineNum);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
**/
@OnMessage
public void onMessage(String message) throws IOException{
message = "客户端:" + message + ",已收到";
System.out.println(message);
for (Session session: sessionPools.values()) {
try {
sendMessage(session, message);
} catch(Exception e){
e.printStackTrace();
continue;
}
}
}
//错误时调用
@OnError
public void onError(Session session, Throwable throwable){
System.out.println("发生错误" + throwable.getMessage());
throwable.printStackTrace();
}
public static void addOnlineCount(){
onlineNum.incrementAndGet();
}
public static void subOnlineCount() {
onlineNum.decrementAndGet();
}
}
4.页面 websocket_view.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<h3>hello socket</h3>
<p>【userId】:<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="20"></div>
<p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>操作:<div><a onclick="openSocket()">开启socket</a></div>
<p>【操作】:<div><a onclick="sendMessage()">发送消息</a></div>
</body>
<script>
var socket;
function openSocket() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
var userId = document.getElementById('userId').value;
var socketUrl="ws://localhost:8080/webSocket/"+userId;
console.log(socketUrl);
if(socket!=null){
socket.close();
socket=null;
}
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
var serverMsg = "收到服务端信息:" + msg.data;
console.log(serverMsg);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
}
}
function sendMessage() {
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else {
// console.log("您的浏览器支持WebSocket");
var toUserId = document.getElementById('toUserId').value;
var contentText = document.getElementById('contentText').value;
var msg = '{"toUserId":"'+toUserId+'","contentText":"'+contentText+'"}';
console.log(msg);
socket.send(msg);
}
}
</script>
</html>
5.controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 页面视图Controller
*
* @author SW
*
*/
@Controller
public class ViewController {
@RequestMapping("/view")
public String websocketView(){
return "websocket_view";
}
}
6.服务启动
启动服务后,直接访问http://localhost:8080/view
点击页面上开启socket后,后端控制台显示:10加入webSocket!当前人数为2
然后点击发送消息,后端控制显示:客户端:{"toUserId":"20","contentText":"hello websocket"},已收到
解决问题:
鉴于有人不是太明白,因此修改一下并配上源码(网上很多,大致都差不多)
添加html,并修改controller访问页面
<!DOCTYPE HTML>
<html>
<head>
<title>WebSocket - Self To Other</title>
</head>
<body>
<input id="message" type="text" />
<button onclick="sendMessage()">发送</button>
<button onclick="closeWebSocket()">关闭</button>
<hr/>
<div id="response"></div>
</body>
<script type="text/javascript">
var websocket = null;
// 判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/selfToOther");
} else {
alert("当前浏览器不支持WebSocket");
}
// 建立连接成功时的回调方法
websocket.onopen = function (event) {
printMessage("green", "建立连接成功!!!");
}
// 连接异常时的回调方法
websocket.onerror = function (event) {
printMessage("red", "连接异常!!!");
};
// 客户端接收消息时的回调方法
websocket.onmessage = function (event) {
printMessage("blue", event.data);
}
// 关闭连接时的回调方法
websocket.onclose = function() {
printMessage("yellow", "关闭连接成功!!!");
}
// 监听窗口关闭事件,当窗口关闭时,主动关闭连接,防止连接未断开时关闭窗口,服务端抛出异常
window.onbeforeunload = function() {
websocket.close();
}
// 发送消息
function sendMessage() {
if (websocket.readyState != 1) {
printMessage("red", "未建立连接或者连接已处于关闭状态!");
} else {
var message = document.getElementById('message').value;
websocket.send(message);
}
}
// 关闭连接
function closeWebSocket() {
websocket.close();
}
// 打印消息
function printMessage(color, text) {
document.getElementById("response").innerHTML += "<font color='" + color +"'>" + text + "</font><br/>";
}
</script>
</html>
启动服务,浏览器打开http://localhost:8080/selfToOther,打开两个窗口,并在窗口发送信息,两个窗口能正常交流,如下图:
窗口1:
窗口2:
在此配上源码,有需要的自行下载: