【问题标题】:Flutter websockets linuxFlutter websockets linux
【发布时间】:2021-05-25 22:06:25
【问题描述】:

我正在 Linux 上构建一个桌面颤振应用程序,但我在 localhost 上的 websockets 遇到了一些问题。我只打算使用 websockets 作为一种方式来交流我的 python 后端和我的颤振应用程序前端,所有这些都在 localhost(没有网络)上,所以如果你想出更好的解决方案,请告诉我!

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

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: sending message
flutter: hello
flutter: sending message
flutter: test
flutter: sending message
flutter: not received

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

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

非常感谢您的帮助!

【问题讨论】:

    标签: python flutter websocket


    【解决方案1】:

    我也遇到过类似的问题,

    尝试:

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

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

      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接收数据。数据变量在你的代码中对应什么?Undefined name 'data'. Try correcting the name to one that is defined, or defining the name.'.非常感谢你的回复!
    • Data 只是一个变量,定义如下: List data = [ ] 。此变量保存来自我的套接字服务器的响应。在我的情况下是一个json。您也可以只打印(事件)以查看是否获得任何数据
    • 太棒了!我在我的 python 服务器上收到 Open 消息!太感谢了!!!!你能解释一下它是如何工作的吗? 'socket.cast' 和 'if (data.isEmpty) data.add(0);' 是什么意思?做?再次,非常感谢!
    猜你喜欢
    • 2019-08-25
    • 2021-07-15
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2022-09-29
    • 2015-04-10
    • 2016-07-30
    相关资源
    最近更新 更多