Skip to content

Commit

Permalink
백엔드 작업 종료(아마도..ㅎㅎ)
Browse files Browse the repository at this point in the history
  • Loading branch information
nwar-Jeon committed Nov 30, 2019
1 parent 540833b commit 715c2e3
Show file tree
Hide file tree
Showing 7 changed files with 101 additions and 21 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@ JPA를 이용한 Repository 패턴을 사용할 예정입니다.
+ Spring Boot
+ Rest
+ Lombok
+ AWS EC2
+ Web Socket

### 참고자료

+ https://victorydntmd.tistory.com/253
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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("*");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<User> optUser = userRepository.findById(userId);
if(!optUser.isPresent()) {
throw new NotFoundException("유저 아이디를 찾을 수 없음.");
}
User user = optUser.get();
Optional<TaxiPot> 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;}
Expand Down
19 changes: 18 additions & 1 deletion src/main/java/kr/hs/dsm/java/taxipot_backend/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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() {
Expand All @@ -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{" +
Expand All @@ -50,6 +65,8 @@ public String toString() {
", age=" + age +
", gender=" + gender +
", trust_point=" + trust_point +
", roomId=" + roomId +
", seatNum=" + seatNum +
'}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import org.springframework.data.repository.CrudRepository;

import java.util.ArrayList;
import java.util.List;

public interface UserRepository extends CrudRepository<User, String> {
ArrayList<User> findAll();
User save(User user);
List<User> findByRoomIdAndSeatNum(int roomId, int seastNum);
}
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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: {
Expand Down Expand Up @@ -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<User> 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);
}

}
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
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) {
return new TaxiPotSocket(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;
}
}
Expand All @@ -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);
}
}

Expand All @@ -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) {
Expand All @@ -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;
}
}

0 comments on commit 715c2e3

Please sign in to comment.