Using Socket in Flutter apps?

As attdona mentioned,

Your server does not speak the websocket protocol but it exposes a plain tcp socket.

So you need a TCP socket and there is a great tutorial on Sockets and ServerSockets which you can find here.

Here's a snippet:

import 'dart:io';
import 'dart:async';

Socket socket;

void main() {
   Socket.connect("localhost", 4567).then((Socket sock) {
   socket = sock;
   socket.listen(dataHandler, 
      onError: errorHandler, 
      onDone: doneHandler, 
      cancelOnError: false);
   }).catchError((AsyncError e) {
      print("Unable to connect: $e");
   });
   //Connect standard in to the socket 
   stdin.listen((data) => socket.write(new String.fromCharCodes(data).trim() + '\n'));
}

void dataHandler(data){
   print(new String.fromCharCodes(data).trim());
}

void errorHandler(error, StackTrace trace){
   print(error);
}

void doneHandler(){
   socket.destroy();
}

Your server does not speak the websocket protocol but it exposes a plain tcp socket.

This is an example that works with a plain tcp socket, adapted from https://flutter.io/cookbook/networking/web-sockets flutter cookbook example:

import 'package:flutter/foundation.dart';
import 'dart:io';
import 'package:flutter/material.dart';

void main() async {
  // modify with your true address/port
  Socket sock = await Socket.connect('192.168.1.129', 10000);
  runApp(MyApp(sock));
}

class MyApp extends StatelessWidget {
  Socket socket;

  MyApp(Socket s) {
    this.socket = s;
  }

  @override
  Widget build(BuildContext context) {
    final title = 'TcpSocket Demo';
    return MaterialApp(
      title: title,
      home: MyHomePage(
        title: title,
        channel: socket,
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  final Socket channel;

  MyHomePage({Key key, @required this.title, @required this.channel})
      : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Form(
              child: TextFormField(
                controller: _controller,
                decoration: InputDecoration(labelText: 'Send a message'),
              ),
            ),
            StreamBuilder(
              stream: widget.channel,
              builder: (context, snapshot) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 24.0),
                  child: Text(snapshot.hasData
                      ? '${String.fromCharCodes(snapshot.data)}'
                      : ''),
                );
              },
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'Send message',
        child: Icon(Icons.send),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _sendMessage() {
    if (_controller.text.isNotEmpty) {
      widget.channel.write(_controller.text);
    }
  }

  @override
  void dispose() {
    widget.channel.close();
    super.dispose();
  }
}

Tags:

Dart

Flutter