From 715c2e3c645c6e8ad3f3df10bcae1e3fddf9c098 Mon Sep 17 00:00:00 2001 From: nwar-Jeon Date: Sun, 1 Dec 2019 04:58:18 +0900 Subject: [PATCH] =?UTF-8?q?=EB=B0=B1=EC=97=94=EB=93=9C=20=EC=9E=91?= =?UTF-8?q?=EC=97=85=20=EC=A2=85=EB=A3=8C(=EC=95=84=EB=A7=88=EB=8F=84..?= =?UTF-8?q?=E3=85=8E=E3=85=8E)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 ++- .../java/taxipot_backend/SocketConfigure.java | 6 ++- .../controller/TaxipotRestController.java | 9 +++- .../dsm/java/taxipot_backend/entity/User.java | 19 +++++++- .../repository/UserRepository.java | 2 + .../taxipot_backend/socket/SocketHandler.java | 34 ++++++++++++-- .../taxipot_backend/socket/TaxiPotSocket.java | 46 +++++++++++++------ 7 files changed, 101 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index c0ba70e..9237f8f 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,8 @@ JPA를 이용한 Repository 패턴을 사용할 예정입니다. + Spring Boot + Rest + Lombok -+ AWS EC2 ++ Web Socket + +### 참고자료 + ++ https://victorydntmd.tistory.com/253 \ No newline at end of file diff --git a/src/main/java/kr/hs/dsm/java/taxipot_backend/SocketConfigure.java b/src/main/java/kr/hs/dsm/java/taxipot_backend/SocketConfigure.java index 8c5ae55..4b65055 100644 --- a/src/main/java/kr/hs/dsm/java/taxipot_backend/SocketConfigure.java +++ b/src/main/java/kr/hs/dsm/java/taxipot_backend/SocketConfigure.java @@ -1,7 +1,9 @@ package kr.hs.dsm.java.taxipot_backend; +import kr.hs.dsm.java.taxipot_backend.repository.UserRepository; import kr.hs.dsm.java.taxipot_backend.socket.SocketHandler; import kr.hs.dsm.java.taxipot_backend.socket.SocketRepository; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; @@ -11,10 +13,12 @@ @EnableWebSocket public class SocketConfigure implements WebSocketConfigurer { + @Autowired + UserRepository userRepository; SocketRepository repository = new SocketRepository(); @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) { - webSocketHandlerRegistry.addHandler(new SocketHandler(repository),"/ws/socket").setAllowedOrigins("*"); + webSocketHandlerRegistry.addHandler(new SocketHandler(userRepository,repository),"/ws/socket").setAllowedOrigins("*"); } } diff --git a/src/main/java/kr/hs/dsm/java/taxipot_backend/controller/TaxipotRestController.java b/src/main/java/kr/hs/dsm/java/taxipot_backend/controller/TaxipotRestController.java index 8e715d0..2c8dd7b 100644 --- a/src/main/java/kr/hs/dsm/java/taxipot_backend/controller/TaxipotRestController.java +++ b/src/main/java/kr/hs/dsm/java/taxipot_backend/controller/TaxipotRestController.java @@ -3,6 +3,7 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import kr.hs.dsm.java.taxipot_backend.entity.TaxiPot; +import kr.hs.dsm.java.taxipot_backend.entity.User; import kr.hs.dsm.java.taxipot_backend.exception.NotFoundException; import kr.hs.dsm.java.taxipot_backend.repository.TaxipotRepository; import kr.hs.dsm.java.taxipot_backend.repository.UserRepository; @@ -37,11 +38,17 @@ public TaxiPot makeTaxipot(@RequestBody TaxiPot taxiPot) { }) @RequestMapping(method = RequestMethod.PATCH, path = "/{roomId}/join") public TaxiPot joinTaxipot(@PathVariable("roomId")Integer roomId, @RequestParam(name = "user_id") String userId, @RequestParam(name = "seat_num")int seatNum) { - if(!userRepository.findById(userId).isPresent()) { + Optional optUser = userRepository.findById(userId); + if(!optUser.isPresent()) { throw new NotFoundException("유저 아이디를 찾을 수 없음."); } + User user = optUser.get(); Optional joinPot = taxipotRepository.findById(roomId); if(joinPot.isPresent()) { + user.setRoomId(roomId); + user.setSeatNum(seatNum); + System.out.println(user.toString()); + userRepository.save(user); switch (seatNum) { case 0 : {joinPot.get().setFirst_seat(userId); break;} case 1 : {joinPot.get().setSecond_seat(userId); break;} diff --git a/src/main/java/kr/hs/dsm/java/taxipot_backend/entity/User.java b/src/main/java/kr/hs/dsm/java/taxipot_backend/entity/User.java index 90c808c..2f05ba2 100644 --- a/src/main/java/kr/hs/dsm/java/taxipot_backend/entity/User.java +++ b/src/main/java/kr/hs/dsm/java/taxipot_backend/entity/User.java @@ -3,6 +3,7 @@ import lombok.Getter; import lombok.Setter; +import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @@ -19,15 +20,21 @@ public class User { int age; boolean gender; int trust_point; + @Column(name = "room_id") + Integer roomId; + @Column(name = "seat_num") + Integer seatNum; public User() {} - public User(String user_id, String user_password, int age, boolean gender, int trust_point) { + public User(String user_id, String user_password, int age, boolean gender, int trust_point, Integer roomId, Integer seatNum) { this.user_id = user_id; this.user_password = user_password; this.age = age; this.gender = gender; this.trust_point = trust_point; + this.roomId = roomId; + this.seatNum = seatNum; } public String getUser_id() { @@ -42,6 +49,14 @@ public void setUser_password(String user_password) { this.user_password = user_password; } + public void setRoomId(Integer roomId) { + this.roomId = roomId; + } + + public void setSeatNum(Integer seatNum) { + this.seatNum = seatNum; + } + @Override public String toString() { return "User{" + @@ -50,6 +65,8 @@ public String toString() { ", age=" + age + ", gender=" + gender + ", trust_point=" + trust_point + + ", roomId=" + roomId + + ", seatNum=" + seatNum + '}'; } } diff --git a/src/main/java/kr/hs/dsm/java/taxipot_backend/repository/UserRepository.java b/src/main/java/kr/hs/dsm/java/taxipot_backend/repository/UserRepository.java index f71c69a..d64cd86 100644 --- a/src/main/java/kr/hs/dsm/java/taxipot_backend/repository/UserRepository.java +++ b/src/main/java/kr/hs/dsm/java/taxipot_backend/repository/UserRepository.java @@ -4,8 +4,10 @@ import org.springframework.data.repository.CrudRepository; import java.util.ArrayList; +import java.util.List; public interface UserRepository extends CrudRepository { ArrayList findAll(); User save(User user); + List findByRoomIdAndSeatNum(int roomId, int seastNum); } diff --git a/src/main/java/kr/hs/dsm/java/taxipot_backend/socket/SocketHandler.java b/src/main/java/kr/hs/dsm/java/taxipot_backend/socket/SocketHandler.java index 1255595..9bc1a38 100644 --- a/src/main/java/kr/hs/dsm/java/taxipot_backend/socket/SocketHandler.java +++ b/src/main/java/kr/hs/dsm/java/taxipot_backend/socket/SocketHandler.java @@ -1,23 +1,33 @@ package kr.hs.dsm.java.taxipot_backend.socket; +import kr.hs.dsm.java.taxipot_backend.entity.User; +import kr.hs.dsm.java.taxipot_backend.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; +import java.util.Optional; + public class SocketHandler extends TextWebSocketHandler { + + UserRepository repository; SocketRepository socketRepo; + Logger logger = LoggerFactory.getLogger(SocketHandler.class); - public SocketHandler(SocketRepository socketRepo) { + public SocketHandler(UserRepository repository, SocketRepository socketRepo) { + this.repository = repository; this.socketRepo = socketRepo; } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { session.sendMessage(new TextMessage("Connect")); + logger.info(session.getId()); } @Override @@ -39,7 +49,7 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) } case "DISCONNECT": { isExistSocket(strToInt(strings[0])); - disconnect(session, strToInt(strings[0])); + disconnect(session, strToInt(strings[0]), strings[2]); break; } default: { @@ -80,8 +90,26 @@ private String[] splitMessage(TextMessage message, String regex) { return message.getPayload().split(regex); } - private void disconnect(WebSocketSession session, int room_id) { + private void disconnect(WebSocketSession session, int room_id, String userId) { //TODO DB에서 USER.ROOMID, SEATNUM 삭제 작업 해줘야함. socketRepo.getSocketMap().get(room_id).onClose(session); + applyUserChange(removeSocketInfoOnUser(repository.findById(userId))); + } + + private User removeSocketInfoOnUser(Optional userOptional) { + if(userOptional.isPresent()) { + User user = userOptional.get(); + user.setRoomId(null); + user.setSeatNum(null); + return user; + } + return null; + } + + private void applyUserChange(User user) { + if(user==null) { + return; + } + repository.save(user); } } diff --git a/src/main/java/kr/hs/dsm/java/taxipot_backend/socket/TaxiPotSocket.java b/src/main/java/kr/hs/dsm/java/taxipot_backend/socket/TaxiPotSocket.java index e7e95f8..5d81188 100644 --- a/src/main/java/kr/hs/dsm/java/taxipot_backend/socket/TaxiPotSocket.java +++ b/src/main/java/kr/hs/dsm/java/taxipot_backend/socket/TaxiPotSocket.java @@ -1,18 +1,23 @@ package kr.hs.dsm.java.taxipot_backend.socket; +import kr.hs.dsm.java.taxipot_backend.entity.User; +import kr.hs.dsm.java.taxipot_backend.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; public class TaxiPotSocket { static Logger logger = LoggerFactory.getLogger(TaxiPotSocket.class); private static WebSocketSession[] sessions = new WebSocketSession[4]; + private int socketId; private TaxiPotSocket(int socket_id) { - + socketId = socket_id; } public static TaxiPotSocket create(int socket_id) { @@ -20,8 +25,10 @@ public static TaxiPotSocket create(int socket_id) { } public void join(WebSocketSession session, int seat_num) { - if(sessions[seat_num]==null) { + logger.info("join : " + session.toString() + seat_num); + if (sessions[seat_num] == null || !sessions[seat_num].isOpen()) { sessions[seat_num] = session; + onMessage(session, "JOIN"); return; } } @@ -37,8 +44,8 @@ public void onOpen(WebSocketSession session) { public void onMessage(WebSocketSession session, String message) { logger.info(message); - for(WebSocketSession receive : sessions) { - sendMessage(checkReceiver(receive,session),message); + for (WebSocketSession receive : sessions) { + sendMessage(session, checkReceiver(isOpen(receive), session), message); } } @@ -47,14 +54,21 @@ public void onError(Throwable t, WebSocketSession session) { } public void onClose(WebSocketSession session) { - for(WebSocketSession receive : sessions) { - sendMessage(checkReceiver(receive,session),"REMOVE"); + for (WebSocketSession receive : sessions) { + sendMessage(session, checkReceiver(isOpen(receive), session), "REMOVE"); } + sessions[getSessionIndex(session)] = null; + } + + private WebSocketSession isOpen(WebSocketSession webSocketSession) { + if(webSocketSession==null) return null; + if(webSocketSession.isOpen()) return webSocketSession; + return null; } - private void sendMessage(WebSocketSession receiver, String message) { - try{ - receiver.sendMessage(new TextMessage(getSessionIndex(receiver) + ":" +message)); + private void sendMessage(WebSocketSession sender, WebSocketSession receiver, String message) { + try { + receiver.sendMessage(new TextMessage(getSessionIndex(sender) + ":" + message)); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { @@ -63,20 +77,24 @@ private void sendMessage(WebSocketSession receiver, String message) { } private int getSessionIndex(WebSocketSession session) { - for(int i=0; i<4; i++) { - sessions[i].equals(session); - return i; + for (int i = 0; i < 4; i++) { + if (isSessionNull(sessions[i])) continue; + if (sessions[i].equals(session)) return i; } throw new NullPointerException("session not found"); } private WebSocketSession checkReceiver(WebSocketSession receive, WebSocketSession session) { - if(receive==null) { + if (receive == null) { return null; } - if(receive.equals(session)){ + if (receive.equals(session)) { return null; } return receive; } + + private boolean isSessionNull(WebSocketSession session) { + return session == null; + } }