카테고리 없음

쿠팡이츠 - 스레드별 클라이언트 처리

joo_coding 2025. 6. 14. 14:09

📨 예시 JSON 메시지

{
  "role": "customer",
  "type": "create_order",
  "data": {
    "user_id": "kim123",
    "store_id": "bbq001",
    "menu": [
      { "item_id": "m001", "qty": 2 },
      { "item_id": "m005", "qty": 1 }
    ],
    "address": "서울 강남구 어딘가"
  }
}

 

 

✅ 클라이언트 스레드 핸들러

void handle_client(int client_sock) {
    char buffer[BUFFER_SIZE];

    while (true) {
        memset(buffer, 0, BUFFER_SIZE); // 버퍼 초기화 (필수)
        ssize_t received = read(client_sock, buffer, BUFFER_SIZE);
        if (received <= 0) {
            cerr << "클라이언트 연결 종료 또는 오류\n";
            close(client_sock);
            return;
        }

        try {
            json request = json::parse(buffer);
            string role = request["role"];
            string type = request["type"];
            json data = request["data"];

            if (role == "customer") {
                handle_customer_request(client_sock, type, data);
            } else if (role == "store") {
                handle_store_request(client_sock, type, data);
            } else if (role == "rider") {
                handle_rider_request(client_sock, type, data);
            } else {
                cerr << "알 수 없는 역할: " << role << endl;
            }

        } catch (json::parse_error& e) {
            cerr << "JSON 파싱 오류: " << e.what() << endl;
        } catch (exception& e) {
            cerr << "처리 중 예외 발생: " << e.what() << endl;
        }
    }
}

 

 

1. 고객 요청 처리

void handle_customer_request(int sock, const string& type, const json& data) {
    if (type == "create_order") {
        // 주문 생성 로직
        cout << "[고객] 주문 요청 수신: " << data.dump(2) << endl;
        // 예: create_order_in_db(data);
        string order_id = "ORD12345"; // 예시
        json response = {
            {"status", "ok"},
            {"order_id", order_id}
        };
        send(sock, response.dump().c_str(), response.dump().length(), 0);
    }
    // 다른 요청 타입 추가 가능 (ex. 주문 상태 조회)
}
 

 

2. 가게 요청 처리

void handle_store_request(int sock, const string& type, const json& data) {
    if (type == "start_cooking") {
        cout << "[가게] 조리 시작 요청: " << data.dump(2) << endl;
        // update_order_status(data["order_id"], "조리중");
    } else if (type == "request_dispatch") {
        cout << "[가게] 라이더 배차 요청: " << data.dump(2) << endl;
        // dispatch_order(data["order_id"]);
    }
}

 

3. 라이더 요청 처리

void handle_rider_request(int sock, const string& type, const json& data) {
    if (type == "start_delivery") {
        cout << "[라이더] 운행 시작: " << data.dump(2) << endl;
        // update_order_status(data["order_id"], "배달중");
        json response = {
            {"status", "ok"},
            {"message", "배달 시작 등록됨"}
        };
        send(sock, response.dump().c_str(), response.dump().length(), 0);
    }
}

 

✅ JSON 메시지 송수신 참고 사항

  • 수신 시 버퍼를 반드시 memset()으로 초기화
  • recv() 또는 read()는 TCP 스트림이므로, 분할 수신이나 구분자 처리가 필요할 수 있음 → 예: 메시지 끝에 \n 또는 \0 삽입
  • 보낼 때는 json.dump()로 직렬화한 뒤 send() 사용