반응형

사용한 패키지

- 1. flutter_client_sse : https://pub.dev/packages/flutter_client_sse

- 2. flutter_local_notifications : https://pub.dev/packages/flutter_local_notifications

 

SSE(Server-Sent Events)란?

- 웹소켓의 역할을 하면서 더 가볍다. 주로 서버에서 받는 작업에 유용하게 사용한다. 웹소켓과 달리 양방향이 아니므로, 요청을 보낼 때는 Ajax를 사용한다.

- 사용 예시: 친구의 상태 업데이트, 주식 시세 표시기, 뉴스피드 또는 기타 자동화된 데이터 푸시 메커니즘(예: 클라이언트 측 웹 SQL 데이터베이스 또는 IndexedDB 객체 저장소 업데이트)

 

플러터 사용 코드 (알림 컨트롤러)

import 'package:app/controller/deviceInfo_controller.dart';
import 'package:app/models/chatting/notify_model.dart';
import 'package:app/notification.dart';
import 'package:get/get.dart';
import 'package:flutter_client_sse/flutter_client_sse.dart';
import 'package:http/http.dart' as http;

class NotifyController extends GetxController {
  static NotifyController get to => Get.find();

  List<NotifyReceive> notifyList = [];

  @override
  void onInit() {
    DeviceInfoController dc = Get.put(DeviceInfoController());
    String Url = 'http://서버주소:9998/notify/${dc.token}';
    SSEClient.subscribeToSSE(
        url: Url,
        header: {
          "Accept": "text/event-stream",
        }).listen((event) {
      // event 받으면 실행되는 부분
      print('알림이 도착했다--------------------------------');
      var receive = notifyReceiveFromJson(event.data as String);
      showNotification(receive.type, receive.content);
      notifyList.add(receive);
      update();
    });
    super.onInit();
  }

  void readAlarm(String noSeq, int uSeq, int index) async {
    // String Url = "http://localhost:9998/notify";
    try {
      await http.put(
          Uri.parse(Url),
          body: {
            "notifySeq" : noSeq,
            "userSeq" : uSeq.toString()
          }
      );
    } catch (e) {
      print('알림 읽음 오류 $e');
    }
    notifyList.removeAt(index);
    update();
  }
}

알림이 도착하면 flutter_local_notification을 활용해 만들어놓은 showNotification 함수를 사용하여 기기에서 푸쉬 알림을 띄우고, 알림을 읽는다면, 알림 배열에서 삭제하는 작업을 수행함.

반응형

'공부하기 > Front-end' 카테고리의 다른 글

Vue 프로젝트 초기 생성  (0) 2023.08.25
Flutter 공부하면서 개발하면서 정리  (0) 2023.08.25
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기