Skip to content
This repository has been archived by the owner on Aug 13, 2022. It is now read-only.

#30 웹소켓을 이용한 1:1 채팅 구현 #32

Open
wants to merge 25 commits into
base: feature/29
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
f455586
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 24, 2020
5fabb1d
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 24, 2020
bf32376
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 25, 2020
4daebd0
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 25, 2020
c19f1ba
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 25, 2020
4e73acc
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 27, 2020
cfdde06
Merge branch 'develop' into feature/30
junshock5 Aug 27, 2020
88e212c
Merge branch 'feature/29' into feature/30
junshock5 Aug 27, 2020
18c4ad4
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 28, 2020
f56371c
Merge branch 'feature/30' of https://github.com/f-lab-edu/used-market…
junshock5 Aug 28, 2020
fc9f045
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 31, 2020
bd8c3b2
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Aug 31, 2020
5a4efeb
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Sep 1, 2020
c5a76b7
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Sep 1, 2020
6e23408
attachFile 잘못올라간거 삭제
junshock5 Sep 1, 2020
f4f1fad
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Sep 3, 2020
8d887b5
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Sep 3, 2020
5fb8d10
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Sep 3, 2020
7d4b6ca
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Sep 6, 2020
825152d
Merge branch 'feature/29' into feature/30
junshock5 Sep 8, 2020
e4e31df
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Sep 12, 2020
f1d226c
Merge branch 'feature/30' of https://github.com/f-lab-edu/used-market…
junshock5 Sep 12, 2020
05eba04
캐싱 만료시간 추가 , DateUtil 필요없는 로그 삭제
junshock5 Sep 12, 2020
fdb1bf9
Merge branch 'feature/29' into feature/30
junshock5 Sep 12, 2020
9717040
#30 웹소켓을 이용한 1:1 채팅 구현
junshock5 Sep 15, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import com.market.server.service.ChattingService;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -40,14 +40,12 @@ public ModelAndView room() {
*/
@PostMapping("/rooms")
@ResponseBody
public List<RoomDTO> createRoom(RoomDTO roomDTO, Model model) {
model.addAttribute("roomDTO", roomDTO);
public List<RoomDTO> createRoom(RoomDTO roomDTO) {
String roomName = roomDTO.getRoomName();

RoomDTO room = null;

if (roomName != null && !roomName.trim().equals("")) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

roomName이 null이면 NPE가 날 것 같네요

int roomNumber = 0;
roomNumber = chattingService.getLastRoomNumber();
int roomNumber = chattingService.getLastRoomNumber();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이것도 동시성문제가 있어보이네요. 이 메소드는 호출할때마다 다른값을 반환하나요? 혹은 같은 값을 반환할수도 있나요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RoomDTO가 정상적으로 등록되지 않았다면 같은값을 반환할 수도 있습니다.

room = RoomDTO.builder()
.roomNumber(++roomNumber)
.roomName(roomName)
Expand Down Expand Up @@ -76,8 +74,7 @@ public List<RoomDTO> getRoom(@RequestBody RoomDTO roomDTO) {
* @return
*/
@GetMapping("/chatting")
public ModelAndView moveRoom(RoomDTO roomDTO, Model model) {
model.addAttribute("roomDTO", roomDTO);
public ModelAndView moveRoom(RoomDTO roomDTO) {
ModelAndView mv = new ModelAndView();
int roomNumber = roomDTO.getRoomNumber();

Expand Down
19 changes: 11 additions & 8 deletions src/main/java/com/market/server/handler/SocketHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
public class SocketHandler extends TextWebSocketHandler {

private List<HashMap<String, Object>> rls = new ArrayList<>(); //웹소켓 세션을 담아둘 리스트 ---roomListSessions
private static final int DEFAULT_FILE_UPLOAD_INDEX = 0;
private static final String FILE_DIRECTORY_NAME = System.getProperty("user.dir") + File.separator + "attachFile" + File.separator;

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
Expand Down Expand Up @@ -65,31 +67,31 @@ public void handleTextMessage(WebSocketSession session, TextMessage message) {
@SneakyThrows
@Override
public void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
int fileUploadIdx = 0;
//바이너리 메시지 발송
ByteBuffer byteBuffer = message.getPayload();
String fileName = DateUtil.getNowTimeToyyyyMMddHHmm(new Date(), ".jpg");
String fileDirectoryName = System.getProperty("user.dir") + File.separator + "attachFile" + File.separator;
File file = new File(fileDirectoryName, fileName);
File file = new File(FILE_DIRECTORY_NAME, fileName);
File dir = new File(FILE_DIRECTORY_NAME);

File dir = new File(fileDirectoryName);
if (!dir.exists()) {
dir.mkdirs();
}

try (FileOutputStream out = new FileOutputStream(file, true); //생성을 위해 OutputStream을 연다.
FileChannel outChannel = out.getChannel(); //채널을 열고)
try (
FileOutputStream out = new FileOutputStream(file, true); //생성을 위해 OutputStream을 연다.
FileChannel outChannel = out.getChannel(); //채널을 열고
) {
byteBuffer.flip(); //byteBuffer를 읽기 위해 세팅
byteBuffer.compact(); //파일을 복사한다.
outChannel.write(byteBuffer); //파일을 쓴다.
} catch (Exception e) {
} catch (IOException e) {
e.printStackTrace();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기도 쓰면 안돼는 메소드를 쓰셨네요

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • e.getMessage(), e.toString()
    • 에러 메세지만 간략하게 보여준다.
    • 두 개의 차이점은 그냥 java exception이냐 보여주는 차이. 찍어보면 알 수 있다.
  • e.printStackTrace()
    • 모두가 아는.. 처음 호출한데서부터 에러 발생한 끝까지 들어간 내용 그대로 보여준다. 말 그대로 보면, stack을 trace 했으니. 처음 호출에서부터 차곡차곡 쌓인 모든 함수들을 그대로 뿌려준다.

e.getMessage(), e.toString() 를 사용해도 될까요??

log.error("파일 전송 실패", e);
}

byteBuffer.position(0); //파일을 저장하면서 position값이 변경되었으므로 0으로 초기화한다.
//파일쓰기가 끝나면 이미지를 발송한다.
HashMap<String, Object> temp = rls.get(fileUploadIdx);
HashMap<String, Object> temp = rls.get(DEFAULT_FILE_UPLOAD_INDEX);
for (String k : temp.keySet()) {
if (k.equals("roomNumber")) {
continue;
Expand All @@ -98,6 +100,7 @@ public void handleBinaryMessage(WebSocketSession session, BinaryMessage message)
try {
wss.sendMessage(new BinaryMessage(byteBuffer)); //초기화된 버퍼를 발송한다.
} catch (IOException e) {
e.printStackTrace();
log.error("sendMessage 실패", e);
}
}
Expand Down
15 changes: 9 additions & 6 deletions src/main/java/com/market/server/service/ChattingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,16 @@
@Log4j2
public class ChattingService {
@Autowired
private ChattingMapper chattingMapper;
private ChattingMapper chattingRoomMapper;

private static final String DEFAULT_ROOMS_SORT_STATUS = "NEWEST";
private static final int DEFAULT_SEARCH_COUNT = 30;
private static final int DEFAULT_PAGING_OFFSET = 0;

// 채팅방 등록
public void register(RoomDTO roomDTO) {
if (roomDTO != null) {
chattingMapper.register(roomDTO);
chattingRoomMapper.register(roomDTO);
} else {
log.error("register ERROR! {}", roomDTO);
throw new RuntimeException("register ERROR! 채팅방 등록 메서드를 확인해주세요\n" + "Params : " + roomDTO);
Expand All @@ -28,15 +32,14 @@ public void register(RoomDTO roomDTO) {
public List<RoomDTO> getAllRooms(RoomDTO roomDTO) {
List<RoomDTO> roomDTOList = null;
if (roomDTO == null)
roomDTOList = chattingMapper.selectRooms("NEWEST", 30, 0);
roomDTOList = chattingRoomMapper.selectRooms(DEFAULT_ROOMS_SORT_STATUS, DEFAULT_SEARCH_COUNT, DEFAULT_PAGING_OFFSET);
else
roomDTOList = chattingMapper.selectRooms(roomDTO.getSortStatus().toString(), roomDTO.getSearchCount(), roomDTO.getPagingStartOffset());
roomDTOList = chattingRoomMapper.selectRooms(roomDTO.getSortStatus().toString(), roomDTO.getSearchCount(), roomDTO.getPagingStartOffset());
return roomDTOList;
}

public Integer getLastRoomNumber() {
Integer result = -2;
result = chattingMapper.getLastRoomNumber();
Integer result = chattingRoomMapper.getLastRoomNumber();
if (result == null)
result = 0;
return result;
Expand Down
16 changes: 13 additions & 3 deletions src/main/java/com/market/server/utils/DateUtil.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.market.server.utils;

import lombok.extern.log4j.Log4j2;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;

@Log4j2
public class DateUtil {

/**
Expand All @@ -13,8 +16,14 @@ public class DateUtil {
* @return 처리 시간의 문자열 202009040159.jpg
* @author topojs8
*/
public static String getNowTimeToyyyyMMddHHmm(Date date, String fileType) {
return new SimpleDateFormat("yyyyMMddHHmm").format(date) + fileType;
private static final ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>();
public static final String getNowTimeToyyyyMMddHHmm(Date date, String fileType) {
SimpleDateFormat sdf = tl.get();
if(sdf == null) {
sdf = new SimpleDateFormat("yyyyMMddHHmm");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 있는지 검사하고
  2. 없으면 새로 생성한다

이거는 thread safe 한가요? 그리고 스레드로컬 사용법에 대해 잘못 이해하고 계신듯 하네요~

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로컬변수여서 thread safe한 줄 알고 있는데 아닐까요??

tl.set(sdf);
}
return sdf.format(date) + fileType;
}

/**
Expand All @@ -28,9 +37,10 @@ private static void parseDate(String dateStr) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
Date date = simpleDateFormat.parse(dateStr);
log.info("Successfully Parsed Date " + date);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로그 포맷팅을 사용해주세요

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

변경했습니다.

System.out.println("Successfully Parsed Date " + date);
} catch (ParseException e) {
System.out.println("ParseError " + e.getMessage());
log.error("ParseError", e);
} catch (Exception e) {
e.printStackTrace();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기도 마찬가지입니다

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

변경했습니다.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

변경이 안되어있네요

}
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ market.server.redis.port=6379
market.server.redis.password=

# expire
# millisecond 600������ �� 10�ð�
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

뭔가 글자가 깨진것 같네요

expire.defaultTime=36288000

#JSP, HTML ModelAndView Path Setting
Expand Down