How do i use Socket in Flutter apps?
Asked Answered
F

3

17

I create a Flutter App. I need to connect my app to local network socket services. As shown below, I can use telnet Connect, Send data and Receive data from the server. I use Flutter web_socket plugin and example. I can connect to the server and send the data but I cannot catch (or get data, it doesn't show anything.) the data. In Flutter google groups one person advised me to use stream instead of StreamBuilder.

To send data I use;         Q101:_:49785:_:ABCDE
And receive data I get;     1:_:2:_:119351:_:NİYAZİ TOROS 

And when I use this example (https://flutter.io/cookbook/networking/web-sockets/) I am getting error on my socket service as:

Q: 28.06.2018 08:53:57->GET / HTTP/1.1
A: 28.06.2018 08:53:57 ->:1:_:1:_:FAIL1

Example:

Last login: Tue Jun 26 15:01:44 on ttys000
Niyazis-MBP:~ niyazitoros$ telnet
telnet> telnet 192.168.1.22 1024
Trying 192.168.1.22...
Connected to 192.168.1.22.
Escape character is '^]'.
Q101:_:49785:_:*************
1:_:2:_:119351:_:NİYAZİ TOROS

Based on @Richard Heap suggestion:

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

void connect(InternetAddress clientAddress, int port) {
  Future.wait([RawDatagramSocket.bind(InternetAddress.anyIPv4, 0)]).then(
      (values) {
    RawDatagramSocket _socket = values[0];
    _socket.listen((RawSocketEvent e) {
      print(e);
      switch (e) {
        case RawSocketEvent.read:
          Datagram dg = _socket.receive();
          if (dg != null) {
            dg.data.forEach((x) => print(x));
          }
          _socket.writeEventsEnabled = true;
          break;
        case RawSocketEvent.write:
          _socket.send(
              new Utf8Codec().encode('Hello from client'), clientAddress, port);
          break;
        case RawSocketEvent.closed:
          print('Client disconnected.');
      }
    });
  });
}

main(List<String> arguments) {
  print("Connecting to server..");
  var address = new InternetAddress('192.168.1.22');
  int port = 1024;
  connect(address, port);
}

And I get this:

/Users/niyazitoros/flutter/bin/cache/dart-sdk/bin/dart --enable-asserts --enable-vm-service:59683 /Users/niyazitoros/IdeaProjects/github/untitled/bin/main.dart
Observatory listening on http://127.0.0.1:59683/

Connecting to the server.
RawSocketEvent.write
Flashboard answered 28/6, 2018 at 7:34 Comment(0)
L
25

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();
}
Lussier answered 6/7, 2018 at 15:45 Comment(1)
I upvoted this, however I'd use }).catchError((Object e) { to avoid "Invalid argument (onError): Error handler must accept one Object..."Platinotype
T
8

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();
  }
}
Triserial answered 28/6, 2018 at 17:36 Comment(5)
thanks attdona. Unfortunately doesnt work with my local ip. But ıt does work with Socket sock = await Socket.connect('52.88.68.92', 1234); Also in this line there is a green curly line. When I hovver my mouse top of it it says "Close instances of dart.core.Sink". I don't understand why doesnt work with my local ip? when I use my macOS and using telnet is working with 192.168.1.22Flashboard
I use: print('sending...'); --- widget.channel.write(_controller.text); --- await new Future.delayed(new Duration(seconds: 5)); ---- print('Sent!!!'); And console I can see that I connected to my network as "connected, I can see "sending and "sent" but when I look at my socket services nothing is showing...Flashboard
I've tested with a real android device and it works. Are you using an emulator?Triserial
yes doesnt work on emulator and real device. when allow my socket listener on DMZ and gave a real ip I connected from internet. Does the socket work with aqueduct as well or I have to look somewhere.Flashboard
I found that I need to return \r\n in socket.write('Q101:_:49785:_:x\r\n'); but I cannot get the information. in socket listen how to get text or stringFlashboard
G
-2
Socket.connect(localhost, port).then((socket){
            print('socket $socket');
            socket.listen((Data){
              print(new Code().decode(Data));
            });
          });
Gignac answered 13/5, 2019 at 7:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.