Flutter websockets linux [英] Flutter websockets linux

查看:28
本文介绍了Flutter websockets linux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Linux 上构建桌面 Flutter 应用程序,但我在本地主机上遇到了一些 websockets 问题.我只打算使用 websockets 作为与我的 python 后端和我的 flutter 应用程序前端进行通信的一种方式,所有这些都在本地主机上(无网络),所以如果您想出更好的解决方案,请告诉我!

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!

python 服务器连接到 flutter 应用程序,如您在终端的输出中看到的那样,但是当 flutter 应用程序向服务器发送消息时,这些消息没有收到:

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:

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

它就留在那里.

这是flutter应用程序的输出:

Heres the output of the flutter app:

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

这是我的python代码(服务器):

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()

这是我的颤振代码:

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();
  }
}

当我做一个

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

发生这种情况:

BrokenPipeError: [Errno 32] Broken pipe

非常感谢您的帮助!

推荐答案

我遇到了类似的问题,

试试:

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

但我没有使用 Flutter 的 Websocket 库,我使用的是 dart.io那是我的代码:

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!"),
  ));
});
}

这篇关于Flutter websockets linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆