SlavCodes

BE AND FE WEBSOCKET

Jan 12th, 2023
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. import grails.transaction.Transactional
  2. import org.springframework.messaging.simp.SimpMessageSendingOperations
  3.  
  4. class MyController {
  5.  
  6. MyService myService
  7. SimpMessageSendingOperations messagingTemplate
  8.  
  9. @Transactional
  10. def addItems() {
  11. def items = request.JSON.items
  12. myService.addItemsToList(items) { progress ->
  13. messagingTemplate.convertAndSend("/topic/progress", [percent: progress])
  14. }
  15. }
  16. }
  17. ------------------
  18. import org.springframework.stereotype.Service
  19.  
  20. @Service
  21. class MyService {
  22.  
  23. List<String> itemsList = []
  24.  
  25. def addItemsToList(List<String> items, Closure progressCallback) {
  26. items.eachWithIndex { item, i ->
  27. itemsList << item
  28. progressCallback(100.0 * (i + 1) / items.size())
  29. }
  30. }
  31. }
  32. -----------------------------------------
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42. import grails.transaction.Transactional
  43. import org.springframework.messaging.simp.SimpMessageSendingOperations
  44.  
  45. class MyController {
  46.  
  47. MyService myService
  48. SimpMessageSendingOperations messagingTemplate
  49.  
  50. @Transactional
  51. def addItems() {
  52. def items = request.JSON.items
  53. myService.itemsList = []
  54. myService.addItemsToList(items)
  55. }
  56. }
  57. --------------
  58. import org.springframework.stereotype.Service
  59.  
  60. @Service
  61. class MyService {
  62.  
  63. List<String> itemsList = []
  64. SimpMessageSendingOperations messagingTemplate
  65.  
  66. def addItemsToList(List<String> items) {
  67. items.eachWithIndex { item, i ->
  68. itemsList << item
  69. messagingTemplate.convertAndSend("/topic/progress", [percent: (100.0 * (i + 1) / items.size())])
  70. }
  71. }
  72. }
  73. -----------
  74.  
  75. FE
  76.  
  77. // Create a WebSocket connection to the server
  78. const socket = new SockJS('/ws');
  79. const stompClient = Stomp.over(socket);
  80.  
  81. // Connect to the server
  82. stompClient.connect({}, function () {
  83. // Subscribe to the "/topic/progress" topic
  84. stompClient.subscribe('/topic/progress', function (message) {
  85. // Parse the progress information from the message
  86. const progress = JSON.parse(message.body);
  87. console.log(`Progress: ${progress.percent}%`);
  88. });
  89. });
  90.  
Advertisement
Add Comment
Please, Sign In to add comment