Skip to content

Commit

Permalink
임시
Browse files Browse the repository at this point in the history
임시

임시

임시

임시
  • Loading branch information
lee1684 committed May 26, 2024
1 parent e8ca533 commit 80b31dd
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 4 deletions.
6 changes: 6 additions & 0 deletions back-end/src/main/java/kr/co/ssalon/chat/ChatPreHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ public Message<?> preSend(Message<?> message, MessageChannel channel) {
String username = jwtUtil.getUsername(accessToken);
accessor.getSessionAttributes().put("username", username);

// if (StompCommand.SEND.equals(accessor.getCommand())) {
// String messageType = accessor.getNativeHeader("MessageType").get(0);
// log.info("messageType = {}", messageType);
// accessor.getSessionAttributes().put("messageType", messageType);
// }

if (StompCommand.CONNECT.equals(accessor.getCommand())) {
String moimId = accessor.getFirstNativeHeader("moimId");
memberToChatRoomIdMap.put(username, moimId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@
@Builder
@AllArgsConstructor
public class Message {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "message_id")
private Long id;

@Column(name = "message_type")
private String messageType;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_meeting_id")
private MemberMeeting memberMeeting;
Expand All @@ -37,13 +41,14 @@ public class Message {

protected Message() {}

public static Message createMessage(MemberMeeting memberMeeting, String message) {
public static Message createMessage(MemberMeeting memberMeeting, String message, String messageType) {
return Message.builder()
.memberMeeting(memberMeeting)
.meetingId(memberMeeting.getMeeting().getId())
.memberId(memberMeeting.getMember().getId())
.message(message)
.sentAt(LocalDateTime.now())
.messageType(messageType)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ public class ChatService {
private final MessageRepository messageRepository;

@Transactional
public MessageDTO saveMessage(Member member, Meeting meeting, String message) throws BadRequestException {
public MessageDTO saveMessage(Member member, Meeting meeting, String message, String messageType) throws BadRequestException {
MemberMeeting memberMeeting = memberMeetingService.findByMemberAndMeeting(member, meeting);
Message messageEntity = Message.createMessage(memberMeeting, message);
Message messageEntity = Message.createMessage(memberMeeting, message, messageType);
messageEntity = messageRepository.save(messageEntity);

return new MessageDTO(messageEntity);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ public class ChatController {
@SendTo("/room/{roomId}")
public MessageDTO chat(SimpMessageHeaderAccessor accessor, @DestinationVariable Long roomId, @Payload Map<String, String> message) throws BadRequestException {
String username = (String) accessor.getSessionAttributes().get("username");
// String messageType = (String) accessor.getSessionAttributes().get("messageType");
Member member = memberService.findMember(username);
Meeting meeting = meetingService.findMeeting(roomId);

// 채팅 메시지 저장
MessageDTO messageDTO = chatService.saveMessage(member, meeting, message.get("message"));
MessageDTO messageDTO = chatService.saveMessage(member, meeting, message.get("message"), "ENTER");

return messageDTO;
}
Expand Down
3 changes: 3 additions & 0 deletions back-end/src/main/java/kr/co/ssalon/web/dto/MessageDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
@Builder
public class MessageDTO {

@NotBlank
private String messageType;
@NotBlank
private String nickname;
@NotBlank
Expand All @@ -28,6 +30,7 @@ public class MessageDTO {
public MessageDTO(Message messageEntity) {
Member messageSendMember = messageEntity.getMemberMeeting().getMember();

this.messageType = messageEntity.getMessageType();
this.nickname = messageSendMember.getNickname();
this.profilePicture = messageSendMember.getProfilePictureUrl();
this.message = messageEntity.getMessage();
Expand Down
104 changes: 104 additions & 0 deletions back-end/src/main/resources/static/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const accessToken = "Bearer " + getCookie('access'); // header or cookie 사용

// 소켓 연결을 위한 객체 생성
const stompClient = new StompJs.Client({
brokerURL: 'wss://ssalon.co.kr/ws-stomp',
connectHeaders: {
Authorization: accessToken,
},
});

// 소켓 연결 시도
function connect() {
stompClient.activate();
}

// 소켓 연결이 된 직후 채팅방 구독(subscribe)
stompClient.onConnect = (frame) => {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/room/1', (greeting) => { // 특정 모임 아이디로 설정
showMessage(JSON.parse(greeting.body));
});
stompClient.publish({
destination: "/send/1", // 특정 모임 아이디로 설정
headers: {
"Authorization": accessToken,
"MessageType": "ENTER",
},
body: JSON.stringify({
'message': "입장하였습니다.",
})
});
};

// 메시지 전송(publish)
function sendMessage() {
stompClient.publish({
destination: "/send/1", // 특정 모임 아이디로 설정
headers: {
"Authorization": accessToken,
"MessageType": "TALK",
},
body: JSON.stringify({
'message': $("#message").val(),
})
});
}

// 메시지를 html에 출력
function showMessage(messageObj) { // messageObj = nickname, message, profilePicture, date
$("#greetings").append("<tr><td>" + messageObj.nickname + " : " + messageObj.message + "</td></tr>");
}

// 기존 채팅 불러오기
function loadChat(chatList) {
// GET /api/chat/{moimId} API 호출
}

// 소켓 연결 여부에 따른 UI 변경
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}

// 소켓 연결 해제
function disconnect() {
stompClient.deactivate();
setConnected(false);
console.log("Disconnected");
}

// 에러 핸들링
stompClient.onWebSocketError = (error) => {
console.error('Error with websocket', error);
};

// 에러 핸들링
stompClient.onStompError = (frame) => {
console.error('Broker reported error: ' + frame.headers['message']);
console.error('Additional details: ' + frame.body);
};

// 버튼 클릭에 따른 함수 실행
$(function () {
$("form").on('submit', (e) => e.preventDefault());
$( "#connect" ).click(() => connect());
$( "#disconnect" ).click(() => disconnect());
$( "#send" ).click(() => sendMessage());
});

// 쿠키 가져오기
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
};
53 changes: 53 additions & 0 deletions back-end/src/main/resources/static/chat.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="/main.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@stomp/[email protected]/bundles/stomp.umd.min.js"></script>
<script src="/app.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being
enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div id="main-content" class="container">
<div class="row">
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="connect">WebSocket connection:</label>
<button id="connect" class="btn btn-default" type="submit">Connect</button>
<button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
</button>
</div>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="message">message?</label>
<input type="text" id="message" class="form-control" placeholder="Your message here...">
</div>
<button id="send" class="btn btn-default" type="submit">Send</button>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetings</th>
</tr>
</thead>
<tbody id="greetings">

</tbody>
</table>
</div>
</div>
</div>
</body>
</html>

0 comments on commit 80b31dd

Please sign in to comment.