当前位置:   article > 正文

【原创】SocketIO使用Vue前端+Java后端做一个后端向浏览器的实时推送功能_socket.io vue2引入配合java使用

socket.io vue2引入配合java使用

一、创建Socket.io的服务端

官网写的已经非常详细了:https://socket.io/get-started/chat/

这里为了省事,直接晒代码了:

1、创建package.json

  1. {
  2. "name": "test_socketio",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "keywords": [],
  10. "author": "",
  11. "license": "ISC",
  12. "dependencies": {
  13. "express": "^4.15.2",
  14. "socket.io": "^2.3.0"
  15. }
  16. }

当然,我的项目名就叫test_socketio,大家可以随意命名。记得创建后npm install

2、创建index.html

这个是一个发送的调试界面,能够验证服务是否启动成功,页面代码来自官网的demo

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>Socket.IO chat</title>
  5. <style>
  6. * { margin: 0; padding: 0; box-sizing: border-box; }
  7. body { font: 13px Helvetica, Arial; }
  8. form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
  9. form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
  10. form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
  11. #messages { list-style-type: none; margin: 0; padding: 0; }
  12. #messages li { padding: 5px 10px; }
  13. #messages li:nth-child(odd) { background: #eee; }
  14. </style>
  15. </head>
  16. <body>
  17. <ul id="messages"></ul>
  18. <form action="">
  19. <input id="m" autocomplete="off" /><button>Send</button>
  20. </form>
  21. <script src="/socket.io/socket.io.js"></script>
  22. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  23. <script>
  24. $(function () {
  25. var socket = io();
  26. $('form').submit(function(e){
  27. e.preventDefault(); // prevents page reloading
  28. socket.emit('chat message', $('#m').val());
  29. $('#m').val('');
  30. return false;
  31. });
  32. socket.on('chat message', function(msg){
  33. $('#messages').append($('<li>').text(msg));
  34. });
  35. });
  36. </script>
  37. </body>
  38. </html>

3、创建index.js

不说别的,直接上代码:

  1. var app = require('express')();
  2. var http = require('http').createServer(app);
  3. var io = require('socket.io')(http);
  4. app.get('/', (req, res) => {
  5. res.sendFile(__dirname + '/index.html');
  6. });
  7. io.on('connection', (socket) => {
  8. console.log('a user connected');
  9. socket.on('disconnect', () => {
  10. console.log('user disconnected');
  11. });
  12. socket.on('ServerIterationBroadcastSend', (data) => {
  13. // INFO: Dechert: 2020/8/13 接收后端发来的广播推送请求
  14. const dataObj = JSON.parse(data)
  15. io.emit(`WebIterationBroadcastReceive`, dataObj.content) // INFO: Dechert: 2020/8/13 向web端发送从Java服务端收到的内容
  16. })
  17. socket.on('ServerIterationPointSend', (data) => {
  18. // INFO: Dechert: 2020/8/13 接收后端发来的针对单一用户的推送请求
  19. const dataObj = JSON.parse(data)
  20. const userId = dataObj.userId
  21. io.emit(`WebIterationPointReceive_${userId}`, dataObj.content) // INFO: Dechert: 2020/8/13 向web端发送从Java服务端收到的内容
  22. })
  23. });
  24. io.emit('some event', {someProperty: 'some value', otherProperty: 'other value'}); // This will emit the event to all connected sockets
  25. http.listen(3000, () => {
  26. console.log('listening on *:3000');
  27. });

注意:我这边后端的项目名叫ServerIteration,后端迭代项目,作为后端经验积累,不停更新迭代的项目框架类的项目。前端项目名叫WebIteration,作用和后端的差不多。由于这两个项目不便透露,我尽量描述的详细一点。

4、运行index.js

node index.js

这样SocketIO的服务端就运行在3000端口上了。

 

二、创建后端发送推送接口

1、创建一个发送推送内容的Service

  1. @Slf4j
  2. @Service
  3. @Transactional
  4. public class SocketIoSendService {
  5. private static final String SERVER_NAME = "ServerIteration";
  6. public MessageModel execute(SocketIoForm model) {
  7. MessageModel messageModel = new MessageModel();
  8. Integer sendType = model.getSendType();
  9. String content = model.getContent();
  10. Long userId = model.getUserId();
  11. if (sendType == null) {
  12. return messageModel.setFail("请选择发送类型");
  13. }
  14. if (StringUtils.isBlank(content)) {
  15. return messageModel.setFail("请输入发送内容");
  16. }
  17. if (sendType == S_SocketIoSendType.POINT) {
  18. if (userId == null) {
  19. return messageModel.setFail("发送给指定用户,请输入用户ID");
  20. }
  21. }
  22. try {
  23. Socket socket = IO.socket("http://127.0.0.1:3000"); // INFO: Dechert: 2020/8/13 连接到SocketIO服务器
  24. socket.connect();
  25. AdvanceHashMap advanceHashMap = new AdvanceHashMap();
  26. advanceHashMap.put("content", content);
  27. if (sendType == S_SocketIoSendType.POINT) {
  28. advanceHashMap.put("userId", model.getUserId());
  29. socket.emit(SERVER_NAME + "PointSend", JSON.toJSONString(advanceHashMap));
  30. } else {
  31. socket.emit(SERVER_NAME + "BroadcastSend", JSON.toJSONString(advanceHashMap));
  32. }
  33. } catch (URISyntaxException e) {
  34. e.printStackTrace();
  35. }
  36. messageModel.setSuccess();
  37. return messageModel;
  38. }
  39. }

2、创建接口Controller

  1. @Slf4j
  2. @RestController
  3. public class SaSocketIoSendController {
  4. @Autowired
  5. private SocketIoSendService service;
  6. @RequestMapping(value = "/saSocketIoSend.sahtml", produces = "application/json;charset=UTF-8", method = {RequestMethod.GET, RequestMethod.POST})
  7. public MessageModel execute(@RequestBody SocketIoForm model, HttpServletRequest request) {
  8. MessageModel messageModel = service.execute(model);
  9. return messageModel;
  10. }
  11. }

其中MessageModel和AdvanceHashMap都是继承自HashMap的,只是对于返回数据的简单封装罢了

三、创建Vue前端

使用vue-cli创建一个Vue项目,这点我不再赘述了,网上例子多得是

其中main.js

  1. import Vue from 'vue'
  2. import App from './App.vue'
  3. import router from './router'
  4. import ElementUi from "element-ui"
  5. import VueSocketIo from 'vue-socket.io';
  6. Vue.config.productionTip = false
  7. Vue.use(ElementUi)
  8. Vue.use(new VueSocketIo({
  9. debug:true,
  10. connection:'127.0.0.1:3000'
  11. }))
  12. new Vue({
  13. router,
  14. render: h => h(App),
  15. }).$mount('#app')

SocketIo.vue

  1. <template>
  2. <div>
  3. <h1 @click="enterHello">SocketIO</h1>
  4. <h3>指定人员接收到的消息为:</h3>
  5. <div>{{receivePointMessage}}</div>
  6. <h3>广播消息为:</h3>
  7. <div>{{receiveBroadcastMessage}}</div>
  8. </div>
  9. </template>
  10. <script>
  11. export default {
  12. name: "SocketIo",
  13. data() {
  14. return {
  15. receivePointMessage: "",
  16. receiveBroadcastMessage: "",
  17. userId: Math.ceil(Math.random() * 100)
  18. }
  19. },
  20. watch: {},
  21. mounted() {
  22. console.log('userId is ' + this.userId)
  23. // INFO: Dechert: 2020/8/13 订阅指定的和广播消息推送接口
  24. this.sockets.subscribe(`WebIterationPointReceive_${this.userId}`, (data) => {
  25. this.receivePointMessage = data
  26. })
  27. this.sockets.subscribe(`WebIterationBroadcastReceive`, (data) => {
  28. this.receiveBroadcastMessage = data
  29. })
  30. },
  31. methods: {
  32. enterHello() {
  33. this.$router.push({
  34. path: "/hello"
  35. })
  36. },
  37. },
  38. sockets: {
  39. connect() {
  40. console.log('socket io is connected!!')
  41. },
  42. },
  43. beforeDestroy() {
  44. // INFO: Dechert: 2020/8/13 销毁订阅
  45. this.sockets.unsubscribe(`WebIterationReceive_${this.userId}`)
  46. this.sockets.unsubscribe(`WebIterationBroadcastReceive`)
  47. }
  48. }
  49. </script>
  50. <style scoped>
  51. </style>

四、测试效果

想要测试效果,请使用Postman,采用POST请求,内容类型为json,浏览器中复制几个同样的页面。指定人员发送时,userId由于是随机的,请在F12的console中找到userId。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/404328
推荐阅读
相关标签
  

闽ICP备14008679号