개발새발
플러터 WebSocket 3 본문
플러터 WebSocket 2에서 만든 stompService를 조금 더 편하게 쓰기 위해 Global class를 만들어 전역에서 편하게 쓰기 위해 바꿀 필요가 있었다
보내야 하는 내용들을 정해두고 플러터에서 버튼에 Global.stomp.(함수 이름) 이런 식으로 부르면 지정된 메세지가 발송하도록 했다
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:stomp_dart_client/stomp_dart_client.dart';
class StompService {
StompClient? stompClient;
bool _isConnected = false; // 처음 연결하면 시간이 걸리기 때문에 메세지가 제대로 가지 않을 수 있다 그렇기 때문에 플래그 값을 이용해서 연결 됐을 때 send 메서드가 실행 되도록 변경했다
void subscribe({required String destination, required String kioskId, required String storeId}) {
_isConnected = false;
stompClient = StompClient(
config: StompConfig(
url: '웹소켓 주소',
beforeConnect: () async {
debugPrint('waiting to connect... ♡⸜(˶˃ ᵕ ˂˶)⸝♡');
debugPrint('connecting...☆ミ(o*・ω・)ノ');
},
onConnect: (frame) {
print('[WS] :: STOMP Connected! Yay! (≧▽≦)');
print('[WS] :: Subscribing to topic... :: hecto :: ᕦʕ •ᴥ•ʔᕤ :: with identifier... ( ☞˙ᵕ˙)☞ :: ${kioskId} AND ${storeId}');
stompClient!.subscribe(
destination: destination,
callback: (frame) {
final payload = json.encode(frame.body);
final payloadHeader = json.encode(frame.headers);
print('[WS] :: Topic Message Received! (*´▽`*) :: $payload');
print('[WS] :: Topic payloadHeader Received! (*´▽`*) :: $payloadHeader');
},
headers: {
'selector': "kioskId = '$kioskId' AND storeId = '$storeId' OR (kioskId = ALL AND storeId = '$storeId')"
},
);
_isConnected = true; //연결이 되면 true로 변경
},
stompConnectHeaders: {
'login': '웹소켓 아이디',
'passcode': '웹소켓 비밀번호'
},
onWebSocketError: (dynamic error) => debugPrint('오류: $error'),
),
);
}
void activate() {
if(stompClient != null){
stompClient!.activate();
print('webSocket 연결');
}
}
void deactivate() {
if(stompClient != null) {
stompClient!.deactivate();
print('webSocket 종료');
}
}
// 보내기 위해서는 _isConnected 의 값을 받은 후 true면 실행 된다
bool send({required String destination, Map<String, String>? headers, required dynamic body}) {
if(_isConnected) { //
stompClient!.send(
destination: destination, -> 어디로 보낼지
headers: headers, -> 헤더 헤더에 포함 될 내용을 넣어준다 형식 지정이 가능하다 또는 받는 쪽의 고유 ID 값을 넣어준다
body: body, -> json 형태의 내용
);
debugPrint('webSocket Send Success $body');
return true; // 보내기 성공
} else {
debugPrint('webSocket Send Fail');
return false; // 실패
}
}
}
import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:hello_world/stomp/firstTest.dart';
import 'package:hello_world/stomp/webSocketTest.dart';
void main() { // 해당 스토어의 해당 키오스크에게 보낸
String kioskId = 'ALL'; //내가 보내야 할 키오스크 아이디
String storeId = '1'; // 스토어 아이디
StompService stompService = StompService();
stompService.subscribe(destination: '/topic/test', kioskId: kioskId, storeId: storeId);
stompService.activate();
bool sendTF = false;
// Timer.periodic(const Duration(seconds: 5), (_) { // 타이머를 걸어서 연결 된 후 5초 뒤에 보내도록
stompService.send(
destination: '/topic/test', //보낼 주소
headers: { // 헤더에서 형식을 정해 준 후 고유 값들을 널어준다
'content-type' : 'application/json',
'kioskId' : kioskId,
'storeId' : storeId
},
body: json.encode({"a": 123}), // json으로 인코딩해서 보낸다
);
// debugPrint('send T/F $sendTF');
// });
Timer.periodic(const Duration(seconds: 10), (_) {
stompService.deactivate();
});
}
'플러터 기초' 카테고리의 다른 글
플러터 생명주기 (0) | 2024.06.18 |
---|---|
플러터 WebSocket 2 (0) | 2024.06.04 |
플러터 WebSocket 1 (0) | 2024.06.04 |
플러터에서 사용하는 Dart 기본 (0) | 2024.06.04 |
플러터 widget이란? (0) | 2024.06.04 |
Comments