Skip to content

Commit

Permalink
feat: ws多订阅示例demo补全
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyueyi committed Nov 30, 2023
1 parent 056c6ae commit 67d2089
Show file tree
Hide file tree
Showing 9 changed files with 500 additions and 7 deletions.
5 changes: 4 additions & 1 deletion spring-case/207-websocket-chat/readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
207-websocket-chat
---

基于websocket的在线聊天应用
基于websocket的在线聊天应用


socketJs 的使用姿势: https://www.cnblogs.com/goloving/p/10746378.html
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,17 @@ public void afterSendCompletion(Message<?> message, MessageChannel channel, bool
log.info("IN: afterSendCompletion: {}, sent: {}", message, sent);
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(message);//消息头访问器
if (headerAccessor.getCommand() == null) return;// 避免非stomp消息类型,例如心跳检测

// 订阅成功,回复一个订阅成功的消息
String uname = (String) headerAccessor.getSessionAttributes().getOrDefault("uname", "-");
if (headerAccessor.getCommand() == StompCommand.SUBSCRIBE) {
// 订阅成功,回复一个订阅成功的消息
String uname = (String) headerAccessor.getSessionAttributes().getOrDefault("uname", "-");
log.info("[IN-After] {} 订阅完成: {}", uname, message);
WsAnswerHelper.publish((String) message.getHeaders().get("simpDestination"), "🔔【系统消息】:欢迎: 【" + uname + "】 加入聊天!");
} else if (headerAccessor.getCommand() == StompCommand.UNSUBSCRIBE) {
// fixme 需要注意,下面这个要求取消订阅时,将订阅的 destination 也传递过来,否则这个离开的消息不知道发送给谁
log.info("[IN-After] {} 取消订阅: {}", uname, message);
WsAnswerHelper.publish((String) message.getHeaders().get("simpSubscriptionId"), "🔔【系统消息】:【" + uname + "】 离开了聊天!");
}

ChannelInterceptor.super.afterSendCompletion(message, channel, sent, ex);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

Expand All @@ -21,14 +21,17 @@ public class ChatController {
@Autowired
private UserService userService;

@Autowired
private SimpMessagingTemplate simpMessagingTemplate;

@GetMapping(path = "/")
public String index() {
return "index";
}

@GetMapping(path = "/chat")
public String chat(Model modelAttribute) {
modelAttribute.addAttribute("uname", userService.getUsernameByCookie());
return "chat";
}

private static final int COOKIE_AGE = 30 * 86400;

public static Cookie newCookie(String key, String session) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package com.git.hui.boot.chat.rest;

import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
Expand Down Expand Up @@ -32,4 +37,20 @@ public String getUsername(String session) {
}
return null;
}

public String getUsernameByCookie() {
ServletRequestAttributes requestAttr = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
if (requestAttr != null) {
HttpServletRequest request = requestAttr.getRequest();
if (request.getCookies() == null) {
return null;
}

Cookie ck = Arrays.stream(request.getCookies()).filter(s -> s.getName().equalsIgnoreCase("l-login")).findAny().orElse(null);
if (ck != null) {
return getUsername(ck.getValue());
}
}
return null;
}
}

Large diffs are not rendered by default.

Large diffs are not rendered by default.

135 changes: 135 additions & 0 deletions spring-case/207-websocket-chat/src/main/resources/static/css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
html {
font-size: 14px;
}

pre {
font-family: monospace
}

.monospace {
font-family: monospace
}

.inline-flex {
display: inline-flex !important
}

.card-body {
min-height: 90vh;
padding: 1.25rem 0 0;
}

.slide-fade-enter-active {
transition: all .3s ease
}

.slide-fade-leave-active {
transition: all .8s cubic-bezier(1, .5, .8, 1)
}

.slide-fade-enter, .slide-fade-leave-to {
opacity: 0;
transform: translateX(10px)
}

.ws-alert {
position: absolute;
top: 2px;
right: 0;
left: 0;
z-index: 65535;
margin: auto;
max-width: 550px;
text-align: center
}

.divider {
clear: both;
overflow: hidden;
margin: 1rem auto;
height: 0
}

.divider-dashed {
border-top: 1px dashed #ccc
}

::-webkit-scrollbar-track-piece {
background-color: #f8f8f8
}

::-webkit-scrollbar {
width: 9px;
height: 9px
}

::-webkit-scrollbar-thumb {
min-height: 28px;
background-color: #ddd;
background-clip: padding-box
}

::-webkit-scrollbar-thumb:hover {
background-color: #bbb
}

.message-box {
max-height: calc(100vh - 220px)
}

.console-box, .message-box {
display: block;
overflow: auto;
padding: 1rem
}

.console-box {
max-height: calc(100vh - 485px)
}

.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
background: #ffffff
}

.hljs, .hljs-subst, .hljs-tag, .hljs-title {
color: #000000
}

.hljs-strong, .hljs-emphasis {
color: #000000
}

.hljs-bullet, .hljs-quote, .hljs-number, .hljs-regexp, .hljs-literal {
color: #000080
}

.hljs-code .hljs-selector-class {
color: #800080
}

.hljs-emphasis, .hljs-stronge, .hljs-type {
font-style: italic
}

.hljs-keyword, .hljs-selector-tag, .hljs-function, .hljs-section, .hljs-symbol, .hljs-name {
color: #808000
}

.hljs-attribute {
color: #800000
}

.hljs-variable, .hljs-params, .hljs-class .hljs-title {
color: #0055AF
}

.hljs-string, .hljs-selector-id, .hljs-selector-attr, .hljs-selector-pseudo, .hljs-type, .hljs-built_in, .hljs-builtin-name, .hljs-template-tag, .hljs-template-variable, .hljs-addition, .hljs-link {
color: #008000
}

.hljs-comment, .hljs-meta, .hljs-deletion {
color: #008000
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ function connect() {

// 其次建立ws链接
const channel = $("#endpoint").val();
const socket = new SockJS('/ws/chat/' + channel);
// const socket = new SockJS('/ws/chat/' + channel);
const socket = new SockJS('/ws/chat/channel');
stompClient = Stomp.over(socket);

stompClient.connect({"uname": $("#uname").val()}, function (frame) {
Expand Down
Loading

0 comments on commit 67d2089

Please sign in to comment.