SpringBoot搭建WebSocket服务

一、环境准备

  • 开发工具: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;

/**
 * WebSocket
 * 
 * @author ZhongLi
 * @date 2020-01-12
 * @version 1.0.0
 */
@ServerEndpoint("/WebSocket/{id}")
@RestController
public class WebSocket {

	// 存储会话
	private static ConcurrentHashMap<String, WebSocket> webSocket = new ConcurrentHashMap<String, WebSocket>();

	private String id;
	private Session session;

	/**
	 * 接入连接回调
	 * 
	 * @param session 会话对象
	 * @param id      会话ID
	 * @throws Exception 异常
	 */
	@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 + "关闭连接");
	}

	/**
	 * 收到客户端发来消息回调
	 * 
	 * @param message
	 */
	@OnMessage
	public void onMessage(String message) {
		System.out.println(this.id + "发来消息:" + message);
	}

	/**
	 * 会话出现错误回调
	 * 
	 * @param error   错误信息
	 */
	@OnError
	public void onError(Throwable error) {

	}

	/**
	 * 发送消息给客户端
	 * 
	 * @param message 消息
	 * @throws IOException 异常
	 */
	public void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
	}

	/**
	 * 给指定的会话发送消息
	 * 
	 * @param id      会话ID
	 * @param message 消息
	 * @throws IOException 异常
	 */
	public void sendMessageToId(String id, String message) throws IOException {
		webSocket.get(id).sendMessage(message);
	}

	/**
	 * 群发消息
	 * 
	 * @param message 消息
	 * @throws IOException 异常
	 */
	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;

/**
 * WebSocketConfig
 * 
 * @author ZhongLi
 * @date 2020-01-12
 * @version 1.0.0
 */
@Configuration
public class WebSocketConfig {
	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}
}

三、新建前端项目

  • 1.新建index.html文件,代码如下

1.新建index.html文件,代码如下

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>WebSocket</title>
	</head>
	<body>
	</body>
	<script type="text/javascript">
		var websocket = null;
		//判断当前浏览器是否支持WebSocket
		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项目地址

  • SpringBootWebSocket

springboot-websocket

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是使用Spring Boot搭建WebSocket的简单示例: 1. 添加依赖 在pom.xml中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 配置WebSocketSpring Boot的配置文件application.properties中添加以下配置: ``` server.port=8080 ``` 3. 编写WebSocket处理器 创建一个WebSocket处理器类,用于处理WebSocket连接和消息。 ```java @Component public class WebSocketHandler extends TextWebSocketHandler { @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); session.sendMessage(new TextMessage("Received: " + payload)); } } ``` 4. 配置WebSocket处理器 创建一个WebSocket配置类,用于配置WebSocket处理器。 ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private WebSocketHandler webSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler, "/ws").setAllowedOrigins("*"); } } ``` 5. 测试WebSocket 在浏览器中打开http://localhost:8080/index.html,并打开浏览器的开发者工具,在控制台输入以下JavaScript代码,连接WebSocket并发送消息: ```javascript var ws = new WebSocket("ws://localhost:8080/ws"); ws.onmessage = function(event) { console.log(event.data); } ws.send("Hello, WebSocket!"); ``` 在控制台中应该可以看到收到的消息,例如: ``` Received: Hello, WebSocket! ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值