패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.3.1

tcp_socket_connection

TCP 소켓을 통해 연결하고 메시지를 수신 및 전송할 수 있는 플러터 패키지입니다.

AndroidiOSmacOSWindowsLinux
30일 다운로드
381
좋아요
43
Pub 점수
150

패키지 설치

flutter pub add tcp_socket_connection

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

플랫폼 간 TCP 소켓 통신을 가능하게 하는 플러터 패키지로, 연결, 수신 및 메시지 전송이 가능합니다. 지속적인 TCP 연결을 설정하고 실시간 데이터 교환을 처리하며 연결 상태를 관리할 수 있는 간단한 인터페이스를 제공합니다. IoT 장치, 사용자 정의 프로토콜 또는 백엔드 통합과 같은 저수준 네트워크 제어가 필요한 애플리케이션에 적합합니다. Android, iOS, macOS, Windows, Linux를 지원하여 크로스플랫폼 호환성을 보장합니다. Dart로 작성되어 기존 플러터 프로젝트에 쉽게 통합됩니다.

사용 사례

  • 실시간 장치 통신
  • 사용자 정의 프로토콜 구현
  • IoT 애플리케이션 네트워킹
  • 백엔드 서비스 통합
  • 크로스 플랫폼 네트워크 앱

주요 기능

  • TCP 연결 관리
  • 메시지 전송 및 수신
  • 크로스 플랫폼 지원
  • 연결 상태 모니터링
  • 소켓 작업을 위한 간단한 API

적합한 대상

  • 실시간 네트워크 앱을 개발하는 개발자
  • 사물인터넷 및 임베디드 시스템 통합
  • 직접적인 TCP 제어가 필요한 응용 프로그램
  • 경량 RPC가 필요한 프로젝트
  • 여러 운영 체제를 대상으로 하는 팀

고려 사항

  • Android/iOS에서 네트워크 권한이 필요합니다
  • 연결 끊김에 대한 수동 오류 처리
  • 내장 암호화 없음 (별도로 TLS 사용)
  • 성숙한 패키지에 비해 문서가 제한적
  • HTTP와 같은 고수준 웹 프로토콜에는 적합하지 않습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

tcp_socket_connection

This is a Flutter package that allows you to connect to a socket over the net. All data is then read using UTF-8.

Getting started

To use this plugin, add tcp_socket_connection as a dependency in your pubspec.yaml file.

Main Example

Here is shown an example where a connection is established and the received message is displayed in a Text widget.

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //Instantiating the class with the Ip and the PortNumber
  TcpSocketConnection socketConnection=TcpSocketConnection("192.168.1.113", 10251);

  String message="";

  @override
  void initState() {
    super.initState();
    startConnection();
  }

  //receiving and sending back a custom message
  void messageReceived(String msg){
    setState(() {
      message=msg;
    });
    socketConnection.sendMessage("MessageIsReceived :D ");
  }

  //starting the connection and listening to the socket asynchronously
  void startConnection() async{
    socketConnection.enableConsolePrint(true);    //use this to see in the console what's happening
    if(await socketConnection.canConnect(5000, attempts: 3)){   //check if it's possible to connect to the endpoint
      await socketConnection.connect(5000, messageReceived, attempts: 3);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text(
          'You have received '+ message,
        ),
      ),
    );
  }
}

Usage

First of all declare a new instance of the TcpSocketConnection class:

TcpSocketConnection socketConnection=TcpSocketConnection(IP_ADDRESS, PORT_NUMBER);

Then, to establish a connection it's used the following method:

await socketConnection.connect(TIMEOUT, CALLBACK_FUNCTION);

The method connect allows you to set a TIMEOUT before finishing attempting to connect, a CALLBACK_FUNCTION that is created by the developer and takes a String as parameter. The CALLBACK_FUNCTION will be called when the message is received.

The word await is really important since the connection requires a little bit of time to be initialized. Write that line of code inside an async method to ensure it doesn't impact the UI.

To send a message use the following method:

socketConnection.sendMessage(MESSAGE);

In case you want to send a message with also an EOM you can directly use the following method:

socketConnection.sendMessageEOM(MESSAGE,EOM);

It will automatically append the EOM (End Of Message) at the end of the MESSAGE.

Examples

Imagine you are receiving a String from a server which states "Confirm?FINISH". In order to read it you have to listen to the server asynchronously until you receive the EOM (End of Message) to be sure that the message is finished. After that you have to split the String and keep only the part you need, in this case "Confirm?". This is all done by the connectEOM method in only 1 line of code!

await socketConnection.connectEOM(TIMEOUT, EOM, CALLBACK_FUNCTION, {ATTEMPTS=1});

Imagine you are receiving a String from a server. With the connect method you can read messages received (that probably need to be elaborated by you: the developer) in only 1 line of code!

await socketConnection.connect(TIMEOUT, CALLBACK_FUNCTION, {ATTEMPTS=1});

Last but not least

If you find this package useful, don't forget to leave a like! I appreciate it!

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.