iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0

Socket.io

注意server side需要使用3.0.3版本

否則flutter client會出現timeout (參考自)

(雖然文檔也有註明, 但就這樣鬼打牆去了半天時間)

這邊工商一下隊友的鐵人賽.

未來有空將會補完與隊友的flutter _WebRTC.

搭建Socket.io server side & web client的傳送門

搭建好了的話便可以實現 flutter client<-> Server <-> web client

本篇將重點放在處理Flutter client端
一樣也是和GetX做結合
Widget部分 全部貼出來篇幅會很冗長 更細部的請參考置底的GitHub link

class SocketIOPage extends GetView<SocketIOPageController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Obx(() {
          final stateString = controller.isOnConnect ? "已連線" : "未連線";
          return Text('聊天室 狀態: $stateString');
        }),
        actions: [
          IconButton(
            icon: Icon(Icons.call),
            onPressed: () {
              controller.makeCall();
            },
          ),
        ],
      ),
      body: GestureDetector(
        onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
        child: SafeArea(
          child: Obx(
            () {
              return Column(
                children: [
                  Expanded(child: _buildMessageListView()),
                  _buildTextFieldRow(),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

controller部分

class SocketIOPageController extends GetxController {
  final textEditingController = TextEditingController();

  late IO.Socket socket;

  final _isOnConnect = false.obs;
  set isOnConnect(value) => this._isOnConnect.value = value;
  get isOnConnect => this._isOnConnect.value;

  final _message = ''.obs;
  set message(value) => this._message.value = value;
  get message => this._message.value;
  
  //應該是要帶變數 但目前先寫a
  final _room = 'a'.obs;
  set room(value) => this._room.value = value;
  get room => this._room.value;
  //應該是要帶變數 但目前先寫Flutter_client
  final _userName = 'Flutter_client'.obs;
  set userName(value) => this._userName.value = value;
  get userName => this._userName.value;

  final _messageList = <String>[].obs;
  get messageList => _messageList.toList();
  
  @override
  onInit() {
    connectSokcetIO();
    super.onInit();
  }

  connectSokcetIO() {
    //因為我架在自己本機, 大家要把ip要換成自己的
    socket = IO.io('ws://192.168.x.xx:8090', <String, dynamic>{
      'transports': ['websocket']
    });

    socket.onConnect((_) {
      print('on connect');
      // socket.emit('msg', 'test');
      isOnConnect = true;
      socket.on('joined', (data) {
        print('joined');
        //room, id
        print(data.runtimeType);
        print(data);
      });
    });

    socket.on('message', (data) {
      print('message: ${data[1]}');
      // print(data.runtimeType);
      // print(data);

      final messageContent = data[1];
      _messageList.add(messageContent);
    });

    socket.onDisconnect((data) {
      print('disconnect');
      print(data);
    });

    socket.onConnectError((data) {
      print(data);
    });

    socket.emit('join', room);
  }

  sendMessage() {
    final sendData = userName + ':' + textEditingController.text;
    socket.emit('message', [room, sendData]);
    textEditingController.text = '';
  }

最後一起的大合體
uEnsomLUU8huX7GXg9KM7Q

本篇的GitHub source code

下一篇將為大家介紹 Native_splash


上一篇
[Day27] Flutter with GetX connectivity
下一篇
[Day29] Flutter with GetX native_splash
系列文
Flutter with GetX, loading*175%歷程 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言