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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ build/
/market
/logs/
/usedMarketServer/attachFile/
/attachFile/
57 changes: 28 additions & 29 deletions src/main/java/com/market/server/handler/SocketHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,27 +35,27 @@ public void handleTextMessage(WebSocketSession session, TextMessage message) {
String rN = (String) obj.get("roomNumber");
HashMap<String, Object> temp = new HashMap<String, Object>();

if(rls.size() > 0) {
for(int i=0; i<rls.size(); i++) {
if (rls.size() > 0) {
for (int i = 0; i < rls.size(); i++) {
String roomNumber = (String) rls.get(i).get("roomNumber"); //세션리스트의 저장된 방번호를 가져와서
if(roomNumber.equals(rN)) { //같은값의 방이 존재한다면
if (roomNumber.equals(rN)) { //같은값의 방이 존재한다면
Copy link
Member

Choose a reason for hiding this comment

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

roomNumber가 null일 수도 있을까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

roomNumber는 pk로 null일수 없습니다.

temp = rls.get(i); //해당 방번호의 세션리스트의 존재하는 모든 object값을 가져온다.
break;
}
}

//해당 방의 세션들만 찾아서 메시지를 발송해준다.
for(String k : temp.keySet()) {
if(k.equals("roomNumber")) { //다만 방번호일 경우에는 건너뛴다.
for (String k : temp.keySet()) {
if (k.equals("roomNumber")) { //다만 방번호일 경우에는 건너뛴다.
continue;
}

WebSocketSession wss = (WebSocketSession) temp.get(k);
if(wss != null) {
if (wss != null) {
try {
wss.sendMessage(new TextMessage(obj.toJSONString()));
} catch (IOException e) {
log.error("sendMessage 실패" , e);
log.error("sendMessage 실패", e);
}
}
}
Expand All @@ -70,15 +70,14 @@ public void handleBinaryMessage(WebSocketSession session, BinaryMessage message)
ByteBuffer byteBuffer = message.getPayload();

String fileName = new SimpleDateFormat("yyyyMMddHHmm'.jpg'").format(new Date());
Copy link
Member

Choose a reason for hiding this comment

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

전역 변수로 만들어놓고 돌려쓸 수 있지 않을까요? 혹은 날짜포맷 유틸로도 분리가 가능할것같네요.
대신 SimpleDateFormat 는 전역변수로 쓰지 못할 것 같습니다. 왜 그럴까요?

Copy link
Collaborator Author

@junshock5 junshock5 Sep 3, 2020

Choose a reason for hiding this comment

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

Synchronization
Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

SimpleDateFormat 인스턴스는 필요한 경우 전역 상수로 선언 할 수 있지만
이 클래스는 스레드로부터 안전하지 않습니다. 여러 스레드가 동시에 액세스하는 경우 동기화해야합니다.

jdk 1.8 doc 참고

Copy link
Member

Choose a reason for hiding this comment

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

그럼 더 효율좋은 코드로 바꿔주세요~

File file = new File("");
String fileDirectoryName = file.getAbsolutePath()+"\\usedMarketServer\\attachFile\\";
String fileDirectoryName = System.getProperty("user.dir") + File.separator + "attachFile" + File.separator;
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.

로컬변수에서 상수로 변경하였습니다.


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

file = new File(fileDirectoryName, fileName);
File file = new File(fileDirectoryName, fileName);
FileOutputStream out = null;
FileChannel outChannel = null;
try {
Expand All @@ -87,33 +86,33 @@ public void handleBinaryMessage(WebSocketSession session, BinaryMessage message)
outChannel = out.getChannel(); //채널을 열고
byteBuffer.compact(); //파일을 복사한다.
outChannel.write(byteBuffer); //파일을 쓴다.
}catch(Exception e) {
log.error("파일 write 실패" , e);
}finally {
} catch (Exception e) {
log.error("파일 write 실패", e);
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.

IOException printStackTrace(); 추가했습니다.

} finally {
try {
if(out != null) {
if (out != null) {
out.close();
}
if(outChannel != null) {
if (outChannel != null) {
outChannel.close();
Copy link
Member

Choose a reason for hiding this comment

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

try-with-resource 를 쓰면 어떨까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

변경했습니다.

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

byteBuffer.position(0); //파일을 저장하면서 position값이 변경되었으므로 0으로 초기화한다.
//파일쓰기가 끝나면 이미지를 발송한다.
HashMap<String, Object> temp = rls.get(fileUploadIdx);
for(String k : temp.keySet()) {
if(k.equals("roomNumber")) {
for (String k : temp.keySet()) {
if (k.equals("roomNumber")) {
continue;
}
WebSocketSession wss = (WebSocketSession) temp.get(k);
try {
wss.sendMessage(new BinaryMessage(byteBuffer)); //초기화된 버퍼를 발송한다.
} catch (IOException e) {
log.error("sendMessage 실패" , e);
log.error("sendMessage 실패", e);
}
}
}
Expand All @@ -127,21 +126,21 @@ public void afterConnectionEstablished(WebSocketSession session) throws Exceptio
System.out.println(url);
String roomNumber = url.split("/chating/")[1];
int idx = rls.size(); //방의 사이즈를 조사한다.
if(rls.size() > 0) {
for(int i=0; i<rls.size(); i++) {
if (rls.size() > 0) {
for (int i = 0; i < rls.size(); i++) {
String rN = (String) rls.get(i).get("roomNumber");
if(rN.equals(roomNumber)) {
if (rN.equals(roomNumber)) {
flag = true;
idx = i;
break;
}
}
}

if(flag) { //존재하는 방이라면 세션만 추가한다.
if (flag) { //존재하는 방이라면 세션만 추가한다.
HashMap<String, Object> map = rls.get(idx);
map.put(session.getId(), session);
}else { //최초 생성하는 방이라면 방번호와 세션을 추가한다.
} else { //최초 생성하는 방이라면 방번호와 세션을 추가한다.
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("roomNumber", roomNumber);
map.put(session.getId(), session);
Expand All @@ -158,8 +157,8 @@ public void afterConnectionEstablished(WebSocketSession session) throws Exceptio
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
//소켓 종료
if(rls.size() > 0) { //소켓이 종료되면 해당 세션값들을 찾아서 지운다.
for(int i=0; i<rls.size(); i++) {
if (rls.size() > 0) { //소켓이 종료되면 해당 세션값들을 찾아서 지운다.
for (int i = 0; i < rls.size(); i++) {
rls.get(i).remove(session.getId());
}
}
Expand All @@ -172,7 +171,7 @@ private static JSONObject jsonToObjectParser(String jsonStr) {
try {
obj = (JSONObject) parser.parse(jsonStr);
} catch (ParseException e) {
log.error("jsonToObjectParser 실패" , e);
log.error("jsonToObjectParser 실패", e);
}
return obj;
}
Expand Down