1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Redis订阅与转发</title> </head> <body> <form>
<input type="hidden" name="userId" value="001"> <input type="hidden" name="username" value="admin"> <label for="chat"> 群组 </label><br> <input id="chat" type="text" name="groupId" placeholder="请输入要发送的群组id"><br> <label for="content"> 信息 </label><br> <textarea id="content" name="content" placeholder="请输入内容"></textarea><br> <button type="submit">提交</button><br> </form> <button onclick="changeGroup(1)">切换频道1</button> <button onclick="changeGroup(2)">切换频道2</button> <button onclick="changeGroup(3)">切换频道3</button> <script src="/js/jquery.js"></script> <script src="/js/sockjs.js"></script> <script src="/js/stomp.js"></script> <script> var socket = new SockJS('/chat-websocket'); var stompClient = Stomp.over(socket); var groupId = 1;
$('form').on('submit', function(event) { event.preventDefault();
const formData = { groupId: $('input[name="groupId"]').val(), userId: $('input[name="userId"]').val(), username: $('input[name="username"]').val(), content: $('textarea[name="content"]').val(), }; sendMessage(formData.userId,formData.username,formData.content,formData.groupId); });
let currentSubscription;
stompClient.connect({}, function (frame) { currentSubscription = stompClient.subscribe('/topic/group/' + groupId, function (messageOutput) { }); });
function sendMessage(userId,username,messageContent, groupId) { stompClient.send("/app/chat.sendMessage", {}, JSON.stringify({ userId: userId, username: username, content: messageContent, groupId: groupId })); }
function subscribeToGroup(groupId) { if (currentSubscription) { currentSubscription.unsubscribe(); }
currentSubscription = stompClient.subscribe('/topic/group/' + groupId, function(message) { }); }
function changeGroup(newGroupId) { subscribeToGroup(newGroupId); }
</script> </body> </html>
|