Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발새발

플러터 WebSocket 2 본문

플러터 기초

플러터 WebSocket 2

개발하는후추 2024. 6. 4. 22:01

이전 내용은 플러터 WebSocket1 보기 바란다

먼저 webSocket을 사용하기 위해서 다트에서 제공하는 STOMP 라이브러리를 가져와야 한다
websocket이 잘 연결되는지 보기 위해 print를 많이 넣어 뒀다

 # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.6
  stomp_dart_client: ^2.0.0 // 이 부분을 추가 한 후 pub get을 한다
import 'dart:core';
import 'dart:core';

import 'package:stomp_dart_client/stomp_dart_client.dart';


import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';

class webSocket {
  late StompClient stompClient;

  StompService(String identifier, String storeId) {
    stompClient = StompClient( 
      config: StompConfig(
        url: '웹소켓을 이용 할 주소 ',
        beforeConnect: () async {
          debugPrint('waiting to connect... ♡⸜(˶˃ ᵕ ˂˶)⸝♡');
          await Future.delayed(const Duration(milliseconds: 200));
          debugPrint('connecting...☆ミ(o*・ω・)ノ');
        },
        onConnect: (frame) {
          print('[WS] :: STOMP Connected! Yay! (≧▽≦)');
          print('[WS] :: Subscribing to topic... :: hecto :: ᕦʕ •ᴥ•ʔᕤ :: with identifier... ( ☞˙ᵕ˙)☞ :: $identifier OR $storeId');
          stompClient.subscribe(
            destination: '/topic/test', // 접속하는 주소
            callback: (frame) {
              final payload = json.encode(frame.body); //보내는 메세지는 json 형식으로 보낸다 
              final payloadHeader = json.encode(frame.headers);
              print('[WS] :: Topic Messaged Received! (*´▽\`*) :: ${json.encode(payload)}');
              print('[WS] :: Topic payloadHeader Received! (*´▽\`*) :: ${json.encode(payloadHeader)}');
            },
            headers: {
              'selector': "JMSCorrelationID = '$identifier' OR JMSCorrelationID = '$storeId'"
            },
          );
        },
        stompConnectHeaders: { // 메세지를 보내기 위해 activeMQ에 접속 하기 위한 아이디 패스워드
          'login': '아이디',
          'passcode': '비밀번호'
        },
        onWebSocketError: (dynamic error) => debugPrint('오류: $error'),
      ),
    );
  }

  void activate() {
    stompClient.activate();
  }

  void deactivate() {
    stompClient.deactivate();
  }

  void send({required String destination, Map<String, String>? headers, // 메세지를 보낼 때 양식
    required dynamic body}) {
    stompClient.send(
      destination: destination,
      headers: headers,
      body: body,
    );
  }
}

 

깃허브: https://github.com/Limdongkeun/flutter_WebSocket

'플러터 기초' 카테고리의 다른 글

플러터 생명주기  (0) 2024.06.18
플러터 WebSocket 3  (0) 2024.06.04
플러터 WebSocket 1  (0) 2024.06.04
플러터에서 사용하는 Dart 기본  (0) 2024.06.04
플러터 widget이란?  (0) 2024.06.04
Comments