Carlos
Carlos

Reputation: 91

Flutter websockets linux

I'm building a desktop flutter application on Linux and I'm having some problems with websockets on localhost. I'm only planning to use the websockets as a way to communicate my python backend and my flutter app frontend, all on localhost (no network) so if you come up with a better solution let me know!

The python server connects to the flutter app as you can see in the output in the terminal, but when the flutter apps sends messages to the server, these are not received:

Output of python:

[STARTING] server is starting...
[LISTENING] Server is listening on localhost
[NEW CONNECTION] ('MYIP', MYPORT) connected.
receiving messages
GET / HTTP/1.1
user-agent: Dart/2.12 (dart:io)
connection: Upgrade
cache-control: no-cache
accept-encoding: gzip
content-length: 0
sec-websocket-version: 13
host: localhost:5052
sec-websocket-extensions: permessage-deflate; client_max_window_bits
sec-websocket-key: SOME LETTERS/NUMBERS
upgrade: websocket


received
receiving messages

And it stays there.

Heres the output of the flutter app:

flutter: sending message
flutter: hello
flutter: sending message
flutter: test
flutter: sending message
flutter: not received

Here's my python code (server):

import socket 


HEADER = 64
PORT = 5052
SERVER = 'localhost'
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

       

def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept()
        print(f"[NEW CONNECTION] {addr} connected.")

        connected = True
        while connected:
            print('receiving messages')
            msg = conn.recv(5000).decode(FORMAT)
            print(msg)
            print('received')

        conn.close()


print("[STARTING] server is starting...")
start()

And here's my flutter code:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'WebSocket Demo';
    return MaterialApp(
      title: title,
      home: MyHomePage(
        title: title,
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

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

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

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _controller = TextEditingController();
  final _channel = WebSocketChannel.connect(
    Uri.parse('ws://localhost:5052'),
  );

  @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'),
              ),
            ),
            SizedBox(height: 24),
            StreamBuilder(
              stream: _channel.stream,
              builder: (context, snapshot) {
                return Text(snapshot.hasData ? '${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) {
      print('sending message');
      _channel.sink.add(_controller.text);
      print(_controller.text);
    }
  }

  @override
  void dispose() {
    _channel.sink.close();
    super.dispose();
  }
}

When I do a

conn.send('hi flutter'.encode())

This happens:

BrokenPipeError: [Errno 32] Broken pipe

Thank you so much in advanced for your help!

Upvotes: 1

Views: 251

Answers (1)

Shajko
Shajko

Reputation: 210

I had a similar problem,

try:

conn.sendall(bytes("Your Mes here","utf-8"))

But i am not using the Websocket lib from Flutter, i used dart.io That was my code:

  void getDataFromServer({String ip, String port}) async{
     await Socket.connect(ip, int.parse(port)).then((socket) async {
     print('Connected to: '
      '${socket.remoteAddress.address}:${socket.remotePort}');
     socket.cast<List<int>>().transform(json.fuse(utf8).decoder).listen((event) {
     setState(() {
      data = event;
      if (data.isEmpty) data.add(0);
    });
  });
  socket.write("open");
}).onError((error, stackTrace){
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text("Etwas stimmt nicht!"),
  ));
});
}

Upvotes: 1

Related Questions