vue项目集成websocket以及后端spring boot的实现
创建后端spring boot工程
打开我们的IDEA创建一个空的工程,空的工程名字叫vue-websocket-spring-boot-demo,接着在该空的工程底下创建一个后端的module,如下:
工程创建成功以后,打开我们的pom.xml引入我们的netty-socketio的maven依赖,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.websocket</groupId>
<artifactId>socket-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>socket-demo</name>
<description>这是一个给予socket-io的后端demo例子</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.7</version>
</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>
接着打开我们的application.yml加入以下的配置,代码如下:
# host在本地测试可以设置为localhost或者本机IP,在Linux服务器跑可换成服务器IP
socketio:
host: localhost
port: 9099
# 设置最大每帧处理数据的长度,防止他人利用大数据来攻击服务器
maxFramePayloadLength: 1048576
# 设置http交互最大内容长度
maxHttpContentLength: 1048576
# socket连接数大小(如只监听一个端口boss线程组为1即可)
bossCount: 1
workCount: 100
allowCustomRequests: true
# 协议升级超时时间(毫秒),默认10秒。HTTP握手升级为ws协议超时时间
upgradeTimeout: 1000000
# Ping消息超时时间(毫秒),默认60秒,这个时间间隔内没有接收到心跳消息就会发送超时事件
pingTimeout: 6000000
# Ping消息间隔(毫秒),默认25秒。客户端向服务器发送一条心跳消息间隔
pingInterval: 25000
server:
port: 8099
接着打开我们的工程在我们的主入口类的同级目录创建一个config包,同时在底下创建PushMessage.java实体类,代码如下:
package com.websocket.demo.config;
/**
* @author linzf
* @since 2019-06-13
* 类描述:socket消息发送实体类
*/
public class PushMessage {
/**
* 当前登陆的用户
*/
private String loginUser;
/**
* 推送的标题
*/
private String title;
/**
* 推送的内容
*/
private String content;
/**
* 空的构造函数
*/
public PushMessage() {
super();
}
/**
* 构造函数
* @param title
* @param content
*/
public PushMessage(String title, String content) {
this.title = title;
this.content = content;
}
public String getLoginUser() {
return loginUser;
}
public void setLoginUser(String loginUser) {
this.loginUser = loginUser;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
接着创建我们的接口类SocketIoService.java代码如下:
package com.github.lazyboyl.vcm.web.core.config.socketio;
public interface SocketIoService {
/**
* 推送的事件
*/
String PUSH_EVENT = "push_event";
/**
* 启动服务
*
* @throws Exception
*/
void start() throws Exception;
/**
* 停止服务
*/
void stop();
/**
* 推送信息
*
* @param pushMessage
*/
void pushMessageToUser(PushMessage pushMessage);
}
接着创建我们的配置了SocketIoConfig.java代码如下:
package com.websocket.demo.config;
import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author linzf
* @since 2019-06-13
* 类描述:socketIo的配置类
*/
@Configuration
public class SocketIoConfig {
@Value("${socketio.host}")
private String host;
@Value("${socketio.port}")
private Integer port;
@Value("${socketio.bossCount}")
private int bossCount;
@Value("${socketio.workCount}")
private int workCount;
@Value("${socketio.allowCustomRequests}")
private boolean allowCustomRequests;
@Value("${socketio.upgradeTimeout}")
private int upgradeTimeout;
@Value("${socketio.pingTimeout}")
private int pingTimeout;
@Value("${socketio.pingInterval}")
private int pingInterval;
/**
* 以下配置在上面的application.yml中已经注明
* @return 实例化socketIo的服务对象
*/
@Bean
public SocketIOServer socketIOServer() {
SocketConfig socketConfig = new SocketConfig();
socketConfig.setTcpNoDelay(true);
socketConfig.setSoLinger(0);
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
config.setSocketConfig(socketConfig);
config.setHostname(host);
config.setPort(port);
config.setBossThreads(bossCount);
config.setWorkerThreads(workCount);
config.setAllowCustomRequests(allowCustomRequests);
config.setUpgradeTimeout(upgradeTimeout);
config.setPingTimeout(pingTimeout);
config.setPingInterval(pingInterval);
return new SocketIOServer(config);
}
}
最后我们实现我们的接口类SocketIoServiceImpl.java代码如下:
package com.websocket.demo.config.impl;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.websocket.demo.config.PushMessage;
import com.websocket.demo.config.SocketIoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author linzf
* @since 2019-06-13
* 类描述:socket的实现类
*/
@Service(value = "socketIOService")
public class SocketIoServiceImpl implements SocketIoService {
/**
* 用来存已连接的客户端
*/
private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();
/**
* socketIo的对象
*/
@Autowired
private SocketIOServer socketIOServer;
/**
* 功能描述:当前的service被初始化的时候执行以下的方法
* @throws Exception
*/
@PostConstruct
private void autoStartUp() throws Exception {
start();
}
/**
* 功能描述:当我们的系统停止的时候关闭我们的socketIo
* @throws Exception
*/
@PreDestroy
private void autoStop() throws Exception {
stop();
}
@Override
public void start() throws Exception {
// 监听客户端连接
socketIOServer.addConnectListener(client -> {
/**
* 此处实现我们的socket的连接的用户的逻辑,此处我前端传的是loginUser这个参数,大家可以根据自己的情况来定义入参
*/
String loginUser = getParamsByClient(client).get("loginUser").get(0);
clientMap.put(loginUser, client);
});
// 监听客户端断开连接
socketIOServer.addDisconnectListener(client -> {
String loginUser = getParamsByClient(client).get("loginUser").get(0);
if (loginUser != null && !"".equals(loginUser)) {
clientMap.remove(loginUser);
client.disconnect();
}
});
// 处理自定义的事件,与连接监听类似
socketIOServer.addEventListener(PUSH_EVENT, PushMessage.class, (client, data, ackSender) -> {
// TODO do something
});
socketIOServer.start();
}
@Override
public void stop() {
if (socketIOServer != null) {
socketIOServer.stop();
socketIOServer = null;
}
}
/**
* 功能描述:发送消息到前端
* @param pushMessage 发送消息的实体
*/
@Override
public void pushMessageToUser(PushMessage pushMessage) {
clientMap.get(pushMessage.getLoginUser()).sendEvent(PUSH_EVENT, pushMessage);
}
/**
* 此方法为获取client连接中的参数,可根据需求更改
*
* @param client
* @return
*/
private Map<String, List<String>> getParamsByClient(SocketIOClient client) {
// 从请求的连接中拿出参数
Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
return params;
}
}
编写一个SocketController.java的调用推送调用类,代码如下:
package com.websocket.demo.controller;
import com.websocket.demo.config.PushMessage;
import com.websocket.demo.config.SocketIoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author linzf
* @since 2019-06-13
* 类描述:测试接口调用类
*/
@RestController
@RequestMapping("/socket")
public class SocketController {
@Autowired
private SocketIoService socketIoService;
@GetMapping("/send")
public String sendMsg(@RequestParam("content")String content,@RequestParam("loginUser")String loginUser){
socketIoService.pushMessageToUser(new PushMessage(loginUser,"",content));
return "OK";
}
}
到此处我们就完成了后端的socketIo的集成了,接着我们实现前端的集成。
创建vue的前端工程
在我们的项目底下创建一个module,如下:
接着我们打开我们的package.json在我们的dependencies底下增加以下的依赖:
"socket.io-client": "^2.2.0"
然后我们在执行cnpm install命令来下载我们的依赖
cnpm install
依赖下载好以后,我们直接打开我们的App.vue页面,改造完的界面如下:
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view/>
</div>
</template>
<script>
import io from 'socket.io-client'
export default {
name: 'App',
mounted () {
let _this = this
let opts = {
query: 'loginUser=linzf'
}
// socketIo连接的服务器信息,就是我们后端配置的信息
let socket = io.connect('http://127.0.0.1:9099', opts)
socket.on('connect', function () {
console.log('连接成功')
})
// 接收后端发送过来的消息
socket.on('push_event', function (data) {
console.log(data)
})
socket.on('disconnect', function () {
console.log('已经下线')
})
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
接着我们分别启动我们的前端工程和后端工程,我们访问http://localhost:8080/#/会看到如下的页面:
看到箭头的为止则说明我们的socketIo已经与后台产生连接了,接着访问我们前面编写好的接口,接着在浏览器中访问http://127.0.0.1:8099/socket/send?content=1231&loginUser=linzf,我们会看到我们的前端页面接收到的信息如下:
那么到此处我们就完成了我们的vue websocket和spring boot的集成了,具体的代码大家可以直接到GitHub的地址直接下载,直接运行来验证结果,GitHub的地址:https://github.com/lazyboyl/vue-websocket-spring-boot-demo