프로그래밍/flutter

flutter socket 연결후 데이타 계속 보내기 mymq 연결후 응답받음

소행성왕자 2023. 6. 28. 15:23

 

 

 

. 서버 실행

[@localhost socket_server]# php server2_php.php

 

SocketManager.dart

import 'dart:io';

class SocketManager {
  late Socket _socket;
  bool _connected = false;

  static const String host = "220.72.212.";  // php server
  static const int port = 25003;

  // static const String host = "13.125.57.";  // mymq
  // static const int port = 9001;

  Future<void> connectToSocket() async {
    try {
      _socket = await Socket.connect(host, port);
      print('Socket connected');

      _connected = true;

      _listenToSocket();
    } catch (e) {
      print('Failed to connect to socket: $e');
      _connected = false;
    }
  }

  void _listenToSocket() {
    _socket.listen(
          (List<int> data) {
        // 데이터 수신 처리
        String message = String.fromCharCodes(data);
        print('Received: $message');
      },
      onError: (e) {
        print('Socket error: $e');
        _disconnect();
      },
      onDone: () {
        print('Socket disconnected');
        _disconnect();
      },
    );
  }

  Future<void> sendData(String message) async {
    if (!_connected) {
      print('Socket is not connected');
      return;
    }

    try {
      _socket.write(message);
      await _socket.flush();
      print('Sent: $message');
    } catch (e) {
      print('Failed to send data: $e');
      _disconnect();
    }
  }

  void _disconnect() {
    _socket?.close();
    _connected = false;
  }
}

위의 코드는 SocketManager 클래스를 정의하고, 소켓 연결과 데이터 전송을 관리하는 기능을 구현합니다. connectToSocket() 함수를 호출하여 TCP 소켓에 접속하고, _listenToSocket() 함수에서 소켓으로부터 데이터를 수신하는 리스너를 등록합니다. sendData() 함수를 사용하여 데이터를 소켓으로 전송합니다. 소켓 에러 또는 소켓 연결 종료 시 _disconnect() 함수를 호출하여 소켓을 닫고 연결 상태를 업데이트합니다.

이 코드 예제를 참고하여 TCP 소켓에 접속하고 유지하는 기능을 구현할 수 있습니다. 주의할 점은 dart:io 패키지는 Flutter 앱의 웹 플랫폼에서는 사용할 수 없으며, 네이티브 플랫폼인 Android 또는 iOS에서만 동작합니다. Flutter 웹 앱에서는 웹 소켓을 사용하여 소켓 통신을 구현해야 합니다.

main.dart

import 'package:flutter/material.dart';
import 'SocketManager.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final socketManager = SocketManager();

  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Socket Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  socketManager.connectToSocket();
                },
                child: Text('Connect to Socket'),
              ),
              ElevatedButton(
                onPressed: () {
                  socketManager.sendData('Hello, Socket!');
                },
                child: Text('Send Data'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

위의 코드 예제에서는 SocketManager 인스턴스를 생성하고, 버튼 위젯을 사용하여 소켓에 연결하고 데이터를 전송하는 기능을 구현합니다.

main() 함수에서는 SocketManager를 생성한 후 MyApp 위젯을 실행합니다.

MyApp 위젯은 MaterialApp을 통해 기본 앱 구조를 설정합니다. Scaffold 위젯을 사용하여 앱의 기본적인 레이아웃을 구성합니다. AppBar 위젯을 추가하여 상단에 타이틀을 표시합니다.

body 위젯에는 Column 위젯을 사용하여 버튼 위젯을 세로로 정렬합니다. 첫 번째 버튼은 소켓에 연결하는 역할을 수행하고, 두 번째 버튼은 데이터를 소켓으로 전송합니다.

위의 실행 코드 예제를 참고하여 Flutter 앱에서 TCP 소켓에 접속하고 데이터를 전송할 수 있습니다. 

추가 mymq 연결하여 응답까지 받아옴

main.dart

import 'package:flutter/material.dart';
import 'SocketManager.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final socketManager = SocketManager();

  static const String hexString = "0000012931334331202020202020202020202020646f6d202020202057313931304130312020202020202020202020202020202020202020202020202020202020203030302e3030302e3030302e303030203030302e3030302e3030302e3030302030302d30302d30302d30302d30302d3030202020533031383238352020202020202020205748202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020207b7b2268223a2262617365222c2263223a225731393130413031222c226d223a22726563697665227d7d2020202020202020202020202020202020202020202020202020202020202020202020202020";

  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Socket Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  socketManager.connectToSocket();
                },
                child: Text('Connect to Socket'),
              ),
              ElevatedButton(
                onPressed: () {
                  socketManager.sendData('Hello, Socket!');
                },
                child: Text('Send Data'),
              ),
              ElevatedButton(
                onPressed: () {
                  socketManager.sendTr(hexString);
                },
                child: Text('Send Tr'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

SocketManager.dart

import 'dart:io';
import 'dart:typed_data';
import 'package:hex/hex.dart';

class SocketManager {
  late Socket _socket;
  bool _connected = false;

/*  static const String host = "220.72.212.";  // php server
  static const int port = 25003;*/

  static const String host = "13.125.57.";  // mymq
  static const int port = 9001;

  Future<void> connectToSocket() async {
    try {
      _socket = await Socket.connect(host, port);
      print('Socket connected');

      _connected = true;

      _listenToSocket();
    } catch (e) {
      print('Failed to connect to socket: $e');
      _connected = false;
    }
  }

  void _listenToSocket() {
    _socket.listen(
      (List<int> data) {
        // 데이터 수신 처리
        //String message = String.fromCharCodes(data);
        //print('Received: $message');
        String hexString = HEX.encode(data);
        print(hexString);
      },
      onError: (e) {
        print('Socket error: $e');
        _disconnect();
      },
      onDone: () {
        print('Socket disconnected');
        _disconnect();
      },
    );
  }

  Future<void> sendData(String message) async {
    if (!_connected) {
      print('Socket is not connected');
      return;
    }

    try {
      _socket.write(message);
      await _socket.flush();
      print('Sent: $message');
    } catch (e) {
      print('Failed to send data: $e');
      _disconnect();
    }
  }

  Future<void> sendTr(String message) async {
    if (!_connected) {
      print('Socket is not connected');
      return;
    }

    List<int> bytes = HEX.decode(message);

    try {
      _socket.add(bytes);
      await _socket.flush();
      print('Sent: $message');
    } catch (e) {
      print('Failed to send data: $e');
      _disconnect();
    }
  }

  void _disconnect() {
    _socket?.close();
    _connected = false;
  }
}