flutter 连接热点进行设备间通信

需要使用 wifi_info_plugin_plus 第三方库获取当前连接热点的 IP; 使用 dart 提供的 dart:io 库创建 socket 连接

整体实现思路,创建socket服务端和客户端用于信息交互, 服务端获取当前网络的 IP 地址, 设置端口号,开启 socket 服务; 客户端需要和服务端在同一网络下链接服务端创建 scoket 的 IP 地址获取信息和发送信息。

1. 建立服务端socket类

import 'dart:io';

import 'package:get/get.dart';

class SocketServerController extends GetxController {

  late ServerSocket serverSocket;
  late Socket? socketParams = null;
  RxInt count = 0.obs; 

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  createSocket(IP,_port)async{
    try {
      serverSocket = await ServerSocket.bind(IP, _port);
      print("socket服务器创建成功");
      serverSocket.listen(handelSocket);
    } catch (e) {
      print(e.toString());
    }
  }

  // 监听socket
  handelSocket(Socket  socket){
    // 只有接收到客户端的消息后才会进行初始化
    socketParams = socket;
    socket.write('Hello, user');
    socket.listen((data) async {
      var str = utf8.decode(data);
      List<dynamic> jsonList = jsonDecode(str);
      List<int> intList = List<int>.from(jsonList.map((item) => item as int));
      Uint8List bytes = Uint8List.fromList(intList);
      var jsonMap = json.decode(utf8.decode(bytes));
      print("接受客户消息 ${jsonMap}")
    }).onDone(() {
      print("服务断开");
      closeSocket();
    });
  }

  // 发送
  void send()async{
    if(socketParams != null){
      socketParams?.write('Hello, Socket Client!');
    }else{
      print("socketParams尚未初始化");
    }
  }

  // 监听关闭
  void closeSocket() {
    // 需要线关闭监听的_serverSocketObj
    if (serverSocket != null) {
      serverSocket.close();
      print('Server Socket closed');
    }
  }
    
}

2.建立客户端连接socket类

import 'dart:io';

class SocketClient {
  final String IP; // 热点IP地址
  final int port; // 端口号

  SocketClient(this.IP,this.port);

  late Socket _socket;

  Future<void> connect() async {
    try {
      clientSocket = await Socket.connect(IP, clientPort);
      // print('Connected to server: $IP:$clientPort');
      print("连接成功 ${IP}:${clientPort}");
      clientStatusAlter();
      sendData("hello server");
      clientSocket?.listen((data) {
         // 因 Data自身是二进制流,需要转两次才可以获取到最终的流
        var str = utf8.decode(data);
        List<dynamic> jsonList = jsonDecode(str);
        List<int> intList = List<int>.from(jsonList.map((item) => item as int));
        Uint8List bytes = Uint8List.fromList(intList);
        var jsonMap = json.decode(utf8.decode(bytes));
        print("接受服务端信息 ${jsonMap}")
      }).onDone(() {
        print("监听到服务端断了");
        clientSocket?.close();
      });
    } catch (e) {
      print(e.toString());
    }
  }

  Future<void> sendData(String data) async {
    try {
      _socket.write(data);
    } catch (e) {
      print(e.toString());
    }
  }

  Future<void> disconnect() async {
    try {
      await _socket.close();
    } catch (e) {
      print(e.toString());
    }
  }
}

使用

创建 服务端socket 实例

import 'package:get/get.dart';
import 'package:wifi_info_plugin_plus/wifi_info_plugin_plus.dart';
import "./utils/socketServer.dart";
import "./app/controllers/socket_server_controller.dart";

class ServerPageController extends GetxController {
  final SocketServerController socketServerController = Get.find();

  RxInt count = 0.obs;
  WifiInfoWrapper? _wifiObject;

  var IP;
  var socket;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() async {
    await socket.closeSocket();
    super.onClose();
  }

  initPlatformState() async {
    WifiInfoWrapper? wifiObject;
    try {
      wifiObject = await WifiInfoPlugin.wifiDetails;
    } catch (err) {
      print("这玩意报错了");
    }
    _wifiObject = wifiObject;
    String ipAddress =
        _wifiObject != null ? _wifiObject!.ipAddress.toString() : "...";
    print("打印这个IP: ${ipAddress}");
    IP = ipAddress;
  }

  // 创建server
  serverButton() async {
    await initPlatformState();
    socketServerController.createSocket(IP, 8888);
  }

  // 发送信息
  send() {
    socketServerController.send();
  }
}

创建客户端实例

import 'package:get/get.dart';
import 'package:wifi_info_plugin_plus/wifi_info_plugin_plus.dart';
import "./utils/socketUser.dart";

class UserController extends GetxController {
  //TODO: Implement UserController

  final count = 0.obs;
  
  WifiInfoWrapper? _wifiObject;
  var IP;
  var socket;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    socket.disconnect();
    super.onClose();
  }

  initPlatformState()async{
    WifiInfoWrapper? wifiObject;
    try {
      wifiObject = await WifiInfoPlugin.wifiDetails;
    }catch(err){
      print("这玩意报错了");
    }
    _wifiObject = wifiObject;
    String ipAddress = _wifiObject != null ? _wifiObject!.ipAddress.toString() : "...";
    print("打印这个IP: ${ipAddress}");
    IP = ipAddress;
  }

  create()async{
    // print(IP);
    socket = SocketClient("192.168.23.106",8888);
    await socket.connect();
  }
  send()async{
    await socket.sendData("hello server");
  }

  void increment() => count.value++;
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇